Vuex跨模块Action读取其他模块Getter获取JWT报undefined错误
错误根因
你在定义refreshContactData这个action时,完全搞错了Vuex给action传参的逻辑。
- Vuex 执行模块内的action时,只会给函数传入一个参数:也就是包含所有上下文的context对象,根本不会按顺序把state、getters、rootState、rootGetters拆成4个独立的位置参数传给你。
- 你现在写的
async refreshContactData( state, getters, rootState, rootGetters )的写法,实际运行时:- 第一个形参
state拿到的是完整的context对象 - 后面三个形参
getters、rootState、rootGetters没有任何入参赋值,全部是undefined - 你访问
rootGetters['user/getJWT']时,因为rootGetters本身就是undefined,自然会抛出Cannot read property 'user/getJWT' of undefined的错误。
- 第一个形参
修复方案
两种可直接用的改法:
- 写法1:只接收第一个context形参,从对象上取需要的属性
async refreshContactData(context) { return axios.get('/test', { headers: { Authorization: 'Bearer ' + context.rootGetters['user/getJWT'] } }).then(response => { console.log(response) }) } - 写法2:最常用的解构写法,直接在第一个形参位置把需要的属性从context对象上解构出来
async refreshContactData({ rootGetters }) { return axios.get('/test', { headers: { Authorization: 'Bearer ' + rootGetters['user/getJWT'] } }).then(response => { console.log(response) }) }
改完可以临时在action里加一行
console.log(rootGetters),确认拿到的是完整的根store getter集合、能正常访问到user/getJWT即可。只要你之前模块挂载的名字和getter路径对应,就不会再报undefined错误。
内容的提问来源于stack exchange,提问作者user3069488
相关产品推荐
相关产品推荐

