Vuex-请勿在变异处理程序之外对vuex存储状态进行变异。突变内部状态改变

问题描述 投票:0回答:1

我正在从主布局调用存储操作(nuxt.js default.vue)然后,我在突变导出中调用状态突变。为什么会出现此错误?

控制台错误:http://prntscr.com/rwvfjf

代码:

default.vue

created () {
  this.$store.dispatch("update_user");
  ...
}

商店(store / store.index.js)

export const state = {
  ...
  state: null, 
}

export const actions {
  ...
  update_user({commit}) {commit("update_user")}
}

export const mutations = {
  async update_user(state) {
    if (state.token == undefined) {
      return
    }
    if (this.$axios.defaults.headers.common["authorization"] == undefined) {
      this.$axios.defaults.headers.common["authorization"] = state.token
    }
    var user = await this.$axios.get("/api/v1/user/@me");
    state.user = user;
  },
}
vuex nuxt.js
1个回答
0
投票

来自the docs

更改必须同步

要记住的一个重要规则是,变异处理函数必须是同步的

似乎您将它们颠倒了。将您的动作和突变重组为:

动作

export const actions = {  // <-- was missing an equals
  ...
  async update_user({ state, commit }) { // <-- state and commit needed
    if (state.token == undefined) {
      return
    }
    if (this.$axios.defaults.headers.common["authorization"] == undefined) {
      this.$axios.defaults.headers.common["authorization"] = state.token
    }
    var user = await this.$axios.get("/api/v1/user/@me");
    commit("update_user", user); // <-- Passing the user data to the mutation
  }
}

静音

export const mutations = {
  update_user(state, user) {
    state.user = user;
  },
}

[另外请注意,异步操作将返回数据,然后将其传递给突变,并在其中将其设置为状态。一旦解决,您也可能会遇到this.$axios错误。如果是这样,请确保要导入它:

import axios from 'axios';

并以类似方式使用它:

if (axios.defaults.headers.common["authorization"] == undefined) {
  axios.defaults.headers.common["authorization"] = state.token
}
© www.soinside.com 2019 - 2024. All rights reserved.