TypeError: 정의되지 않은 저장소 디스패치 vuex의 속성 'token'을 읽을 수 없습니다.
저는 Vuex 스토어를 사용하는 vue 컴포넌트를 가지고 있습니다.하지만 난...
TypeError: Cannot read property 'token' of undefined
에러. 왜 그런지 모르겠어.코드는 다음과 같습니다.
main.js:
import Vue from 'vue'
import Vuex from 'vuex';
import App from './App.vue'
import router from './router';
import "./assets/css/tailwind.css";
import '@/assets/css/tailwind.css';
import store from './store';
Vue.config.productionTip = false;
Vue.use(Vuex);
new Vue({
router, store,
render: h => h(App),
}).$mount('#app');
in store/indes.js:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
},
state: {
token: ''
}
})
Generic Form에서.vue:
methods: {
execute() {
console.log("GenericForm.vue")
if (this.inputFunction) {
this.inputFunction()
}
this.register()
},
register () {
console.log("register()")
try {
const response = AuthenticationService.register({
email: 'testss',
password: 'frgr'
})
this.$store.dispatch('setToken', response.data.token)
this.$store.dispatch('setUser', response.data.user)
this.$store.router.push({
name: 'songs'
})
} catch (error) {
console.log(error)
/*
this.error = error.response.data.error
*/
}
}
}
이 에러는, 다음의 코드 라인에서 발생합니다.
this.$store.dispatch
어떤 도움이라도 감사합니다.
편집:
인증 서비스js
import api from './api'
export default {
register (credentials) {
return api().post('register', credentials)
}
}
api.module
import axios from 'axios'
export default() => {
return axios.create({
baseURL: 'http://localhost:8081'
})
};
추가 후console.log
다음과 같습니다.
편집 2:
새로운 방법:
register: async () => {
console.log("register()")
const response = AuthenticationService.register({
email: 'testss',
password: 'frgr'
}).then((response) => {
console.log(response)
/* this.$store.dispatch('setToken', response.data.token)
this.$store.dispatch('setUser', response.data.user)*/
this.$store.router.push({
name: '/test'
})
});
}
에러가 나다
this.$store.router.push({
name: '/test'
})
행:
응답은 정상적으로 기록됩니다.
다음 두 가지 문제가 있습니다.
첫 번째 문제:
다음 코드:
register(credentials) {
return api().post('register', credentials)
}
를 반환하고 있습니다.Promise
(이것에는data
소유물.당신이 원하는 것은 그 공리들에 접근해서response
그 약속에 싸여있으니까, 넌 둘 중 하나야.
- 불러
then
약속대로
AuthenticationService.register({...}).then((response) => {
console.log(response.data.token) // 'foo'
});
- 사용하다
async/await
Vue 컴포넌트 내부
두 번째 문제
저장소가 정의되지 않는 원인은 화살표 함수를 사용하는 것입니다.그register()
메서드에는 화살표가 없어야 합니다.화살표가 삭제되면 오류는 발생하지 않습니다(스토어 및 라우터가 정의됩니다).
async register() {
console.log("register()")
const response = AuthenticationService.register({
email: 'testss',
password: 'frgr'
}).then((response) => {
console.log(response)
console.log(this.$store)
this.$router.push({
name: 'ha'
})
});
}
즉, 이 명령어는data
의 특성response
정의되어 있지 않습니다.
이요?AuthenticationService.register
메서드 비동기?
그런 것 같아요.이 경우 코드는 다음 시간 전에 계속됩니다.response
개체가 올바르게 확인되었습니다.
잠깐 쉬었다가 달려라console.log(response)
메서드가 비동기일 경우 해결되지 않은 약속이 표시될 수 있습니다.
그렇지 않으면 메서드가 아무것도 반환하지 않고 대신 콜백을 사용하는 경우 정의된 내용이 전혀 표시되지 않을 수 있습니다.
언급URL : https://stackoverflow.com/questions/67142028/typeerror-cannot-read-property-token-of-undefined-store-dispatch-vuex
'programing' 카테고리의 다른 글
Java 형식의 yyy-MM-dd 형식의 달력 날짜 (0) | 2022.07.05 |
---|---|
직렬화 및 직렬화 해제 중 JSON 속성의 다른 이름 (0) | 2022.07.05 |
쿠키가 서버에서 캐시하는 vuej 및 vuex에 http only 플래그를 사용하여 쿠키를 설정하는 방법(Laravel) (0) | 2022.07.05 |
Vuex Store 및 계산된 속성을 사용하여 컴포넌트에 전달된 객체 배열을 루프하려면 어떻게 해야 합니까? (0) | 2022.07.05 |
Vuetify 외부 페이지 번호가 표시되지 않음 (0) | 2022.07.03 |