Home > front end >  NuxtJS and Firebase: Error: [vuex] do not mutate vuex store state outside mutation handlers
NuxtJS and Firebase: Error: [vuex] do not mutate vuex store state outside mutation handlers

Time:10-12

In my NuxtJS app when I try to update a user's photoURL, I get the following error:

client.js?06a0:103 
        
       Error: [vuex] do not mutate vuex store state outside mutation handlers.
    at assert (vuex.esm.js?2f62:135)
    at Vue.store._vm.$watch.deep (vuex.esm.js?2f62:893)
    at invokeWithErrorHandling (vue.runtime.esm.js?2b0e:1863)
    at Watcher.run (vue.runtime.esm.js?2b0e:4584)
    at Watcher.update (vue.runtime.esm.js?2b0e:4558)
    at Dep.notify (vue.runtime.esm.js?2b0e:730)
    at Object.reactiveSetter [as photoURL] (vue.runtime.esm.js?2b0e:1055)
    at updateProfile (index-d81b283a.js?6899:5314)

Here's the code that is causing the issue:

    async updateAvatar() {
      const auth = getAuth()
      try {
        await updateProfile(auth.currentUser, {
          photoURL: this.imageSrc.secure_url
        })
        await setDoc(
          doc(db, 'users', this.userProfile.uid),
          {
            avatar: {
              ...this.imageSrc
            }
          },
          {
            merge: true
          }
        )
        console.log('avatar updated!')
      } catch (error) {
        console.log(error)
      }
    },

If I comment out the updateProfile() it works fine, but if I put it back, I then get the error. What am I doing wrong?

CodePudding user response:

Apparently using the Firebase Auth method: updateProfile() triggered an onAuthStateChanged update. So, doing this:

updateProfile(auth.currentUser, {
          photoURL: this.imageSrc.secure_url
        })

...caused an update to to Auth Observer because there was provider data being modified (avatar image) and this caused the following code to run:

  onAuthStateChangedAction({ commit, dispatch }, authUser) {
    const { displayName, email, emailVerified, photoURL, uid } = authUser
    commit('SET_AUTH_USER', {
      displayName,
      email,
      emailVerified,
      photoURL,
      // providerData, // causes vuex mutation error
      uid
    })
    console.log('set Auth User to store')
    dispatch('getUserProfile', authUser)
  },

The culprit was the providerData property which had modified some reference data that was different than what Vuex was storing, hence the Vuex error.

Further, I saw this:

Do not save the authUser directly to the store, since this will save an object reference to the state which gets directly updated by Firebase Auth periodically and therefore throws a vuex error if strict != false.

So, removing providerData from my onAuthStateChanged action fixed the issue.

  • Related