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

在我的 NuxtJS 应用程序中,当我尝试更新用户的照片 URL 时,出现以下错误:

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)

这是导致问题的代码:

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

如果我注释掉 updateProfile() 它工作正常,但如果我把它放回去,我就会得到错误。我做错了什么?

显然使用了 Firebase Auth 方法:updateProfile() 触发了 onAuthStateChanged 更新。所以,这样做:

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

...导致对 Auth Observer 的更新,因为有提供者数据被修改(头像图像),这导致以下代码 运行:

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

罪魁祸首是 providerData 属性 它修改了一些与 Vuex 存储的不同的参考数据,因此 Vuex 错误。

此外,我看到this

不要将 authUser 直接保存到存储中,因为这将保存一个对象引用到状态,该状态由 Firebase Auth 定期直接更新,因此抛出一个 vuex 错误如果严格!=假。

因此,从我的 onAuthStateChanged 操作中删除 providerData 解决了这个问题。