You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 15:30:55