Vuex & VueJS (do not mutate vuex repository state outside mutation handlers)

I am trying to create a listenAuth function that looks onAuthStateChanged "in firebase to notify vuex store strong> when a user has logged in or out. As far as I can tell, I only change state.authData using a mutation handler if I'm missing something ?

I get an error message:

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

Here is my javascript App.vue (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 is my action (changeAuth) function

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

Here is my store (parts that matter)

 const mutations = { AUTH_CHANGED (state, authData) { state.authData = authData } } const state = { authData: {} } 
+7
source share
3 answers

I also ran into this problem. My shop:

  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})) } } 

Fixed it by replacing state.items = payload.items with:

 state.items = payload.items.slice() 

The reason is that arrays are stored as links in Javascript, and payload.items will most likely be changed outside of Vuex. Therefore, we should simply use a new copy of payload.items .

For state objects use:

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

And do not use JSON.parse(JSON.stringify(someObj)) as it is much slower.

+10
source

After dealing with the same problem, I found that the error only occurs when trying to save auth / user data in Vuex state.

Change from ...

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

... before...

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

will solve your case.

+4
source

I had this problem too and I used lodash to clone data

 state.someStatehere = $lodash.cloneDeep(data) 
0
source

All Articles