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

NuxtJS Store中无法访问$axios出现undefined报错求助

问题原因
  • 你使用箭头函数定义了Vuex action,箭头函数会绑定外层作用域的this,而Nuxt调用store action时不会将Vue实例绑定到action的this上,因此此处this为undefined,自然无法读取$axios属性。
  • @nuxtjs/axios模块默认会将$axios实例注入到store action的上下文参数中,不需要通过this访问。
解决方案

直接修改你的store action代码,从上下文参数中解构出$axios使用即可,修改后的代码如下:

export const actions = {
  // 从上下文参数中新增解构$axios
  AUTH_REQUEST: ({commit, dispatch, $axios}, user) => {
    return new Promise((resolve, reject) => {
      commit('AUTH_REQUEST')
      // 直接使用解构得到的$axios,不需要加this
      $axios({url: 'authentication_token', data: user, method: 'POST'})
        .then(resp => {
          const token = resp.data.token
          localStorage.setItem('jwt', token)
          commit('AUTH_SUCCESS', token)
          dispatch('USER_REQUEST')
          resolve(resp)
        })
        .catch(err => {
          commit('AUTH_ERROR', err)
          localStorage.removeItem('jwt')
          reject(err)
        })
    })
  }
}

如果你确实需要通过this访问$axios,也可以将箭头函数改为普通函数定义action,此时this会指向当前store实例,可以正常访问挂载的$axios属性。

额外注意点
  • 当前你的getters定义是返回对象的函数,不符合Nuxt store的写法规范,应该直接导出对象,否则可能出现getters无法正常读取的问题:
export const getters = {
  isAuthenticated: state => !!state.token,
  authStatus: state => state.status
}
  • 如果你的项目开启了SSR,直接使用localStorage存储token会导致服务端无法读取用户身份,建议使用cookie存储token适配服务端渲染场景。

内容的提问来源于stack exchange,提问作者FindL

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:18:02