Axios 인터셉터 내에서 Vuex 스토리지 변환에 액세스할 수 없습니다.
편집: 이 질문은 매우 혼란스러웠기 때문에 기본적으로 동일한 코드 예제와 동일한 장면으로 다시 씁니다.
서버로부터 401 에러가 송신되었을 때, 나는 그것을 하려고 하고 있다..commit
인터셉터에서 내 vuex 스토리지로:
import axios from 'axios';
import { store } from '../store/store';
export default function execute() {
axios.interceptors.request.use(function(config) {
const token = store.state.token;
if(token) {
config.headers.Authorization = `Bearer ${token}`;
//console.log(config);
return config;
} else {
return config;
}
}, function(err) {
return Promise.reject(err);
});
axios.interceptors.response.use((response) => {
return response;
}, (err) => {
console.log(err.response.status);
if(err.response.status === 401) {
this.$store.commit('logout');
}
console.log('err'); // this doesnt even console log
return Promise.reject(err);
});
}
하지만 그것은 오류를 던지고 있다.
TypeError: 정의되지 않은 속성 '$store'를 읽을 수 없습니다.
at eval (httpInterceptor.js?bdcd:22)
내가 왜 수입하는 게 맞다고 생각하는지 모르겠어.
화살표 기능을 사용하고 있습니다만, 화살표 기능 없이 시도했지만 위와 같은 에러가 발생합니다.
main.js에서 인터셉터를 실행하여 Import하여 호출합니다(import interceptor from './helpers/httpInterceptor.js'; interceptor();
)
vuex 스토리지 파일은 다음과 같습니다.
import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
logged: false,
token: ''
},
mutations: {
login: (state, response) => {
if(response) {
state.logged = true;
state.token = response;
console.log('state updated');
console.log('state.logged flag is: '+state.logged);
console.log('state.token: '+state.token);
}
},
logout: (state) => {
state.logged = false;
state.token = '';
}
},
plugins: [
createPersistedState()
]
});
Vue 인스턴스에 할당하고 있습니다.
new Vue({
el: '#app',
router,
store,
template: '<app/>',
components: { app }
});
이 인터셉터에서는 돌연변이를 사용할 수 없는 이유, 문제의 원인 및 해결 방법
네, 고쳤습니다.그래서 제가 잘못한 것은 문서 예시를 따르는 것입니다.this.$store....
컴포넌트 방식으로 사용해도 괜찮습니다.변수처럼 Import 했을 때
import { store } from '../store/store';
갈아입어야겠다
this.$store.commit('logout');
로.
store.commit('logout');
지금은 잘 되고 있어요.
언급URL : https://stackoverflow.com/questions/49632461/cant-access-vuex-storage-mutation-inside-axios-interceptor
'programing' 카테고리의 다른 글
Nuxt/Vue에서 이벤트 청취자 제거 (0) | 2022.08.22 |
---|---|
Vue 3이 Vuex 스토어 모듈을 인식하지 못하는 이유는 무엇입니까? (0) | 2022.08.22 |
메모리 주소가 아닌 경우 C 포인터는 정확히 무엇입니까? (0) | 2022.08.22 |
Vue.js 2 마우스 엔트리, 마우스 탈퇴 및 콘텐츠 드롭다운을 처리하는 방법 (0) | 2022.08.16 |
어레이 Vuex에서 항목을 제거할 수 없습니다. (0) | 2022.08.15 |