首页 文章

Vuex和VueJS(不要在突变处理程序之外改变vuex存储状态)

提问于
浏览
6

我正在尝试创建一个 listenAuth 函数,在 firebase 中观察“ onAuthStateChanged ”以在用户登录或注销时通知 vuex store . 据我所知,我错过了什么?

I'm getting the error:

[vuex] Do not mutate vuex store state outside mutation handlers.

Here's my App.vue javascript (from my component)

<script>
// import Navigation from './components/Navigation'
import * as actions from './vuex/actions'
import store from './vuex/store'
import firebase from 'firebase/app'

export default {
  store,
  ready: function () {
    this.listenAuth()
  },
  vuex: {
    actions,
    getters: {
      authData: state => state.authData,
      user: state => state.user
    }
  },
  components: {
    // Navigation
  },
  watch: {
    authData (val) {
      if (!val) {
        this.redirectLogin
        this.$route.router.go('/login')
      }
    }
  },
  methods: {
    listenAuth: function () {
      firebase.auth().onAuthStateChanged((authData) => {
        this.changeAuth(authData)
      })
    }
  }
}
</script>

Here's my action (changeAuth) function

export const changeAuth = ({ dispatch, state }, authData) => {
  dispatch(types.AUTH_CHANGED, authData)
}

Here's my store (the parts that matter)

const mutations = {
  AUTH_CHANGED (state, authData) {
    state.authData = authData
  }
}

const state = {
  authData: {}
}

2 回答

  • 9

    我也遇到过这个问题 . 我的商店:

    state: {
        items: []
      },
      mutations: {
        SetItems (state, payload) {
          // Warning
          state.items = payload.items
        }
      },
      actions: {
        FetchItems ({commit, state}, payload) {
          api.getItemsData(payload.sheetID)
            .then(items => commit('SetItems', {items}))
        }
      }
    

    通过将 state.items = payload.items 替换为:

    state.items = payload.items.slice()
    

    原因是数组在Javascript中存储为引用,而有效负载.items可能会在Vuex之外进行更改 . 因此,我们应该使用有效的payload.items的新副本 .

    对于状态对象,请使用:

    state.someObj = Object.assign({}, payload.someObj)
    

    并且不要使用 JSON.parse(JSON.stringify(someObj)) ,因为它要慢得多 .

  • 3

    在遇到同样的问题之后,我发现错误只发生在我们尝试将auth / user数据存储在Vuex状态时 .

    改变...

    const mutations = {
      AUTH_CHANGED (state, authData) {
        state.authData = authData
      }
    }
    

    ...至...

    const mutations = {
      AUTH_CHANGED (state, authData) {
        state.authData = JSON.parse(JSON.stringify(authData))
      }
    }
    

    会解决你的情况 .

相关问题