Vuex认证出现TypeError:无法在字符串上创建'token'属性,如何解决?
问题解决方法
你的错误源于两个关键的语法/用法错误,修正后即可解决问题:
错误1:Mutation参数顺序颠倒
Vuex 的 mutation 方法第一个参数固定为 state,第二个才是传递过来的载荷(payload)。你把 access_token 放在了第一个参数位置,导致原本的 state 被当成 token 传入,而 access_token 参数实际接收到的是 state 对象,这就是为什么你看到 mutation 里接收的数据是对象。
错误2:赋值语句语法错误
state.token = this,access_token 里的逗号是运算符,且此处完全不需要使用 this,错误的语法导致代码逻辑混乱,最终触发了字符串无法添加属性的报错。
修正后的完整代码
import axios from "axios" export default{ namespaced: true, state: { token: null, user: null }, mutations: { // 修正参数顺序:第一个为state,第二个为access_token SET_TOKEN(state, access_token){ console.log(access_token) // 现在能正确打印token字符串 state.token = access_token // 修正赋值语法 }, }, actions: { async loginUser({ dispatch }, form) { let response = await axios.post('/api/auth/login', form) dispatch('attempt', response.data.data.access_token) }, async attempt({ commit }, access_token){ commit('SET_TOKEN', access_token) } } }
补充说明
修正后,mutation 会正确接收 token 字符串,将其赋值给 state.token,不会再出现 Cannot create property 'token' on string 错误——这个错误的本质是你错误地把 state 参数当成了字符串,试图给字符串添加属性,自然会触发类型错误。
内容的提问来源于stack exchange,提问作者ken mutesh
相关产品推荐
相关产品推荐

