Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

为什么Vuex的mutation中不能做异步操作? #42

Open
GGXXMM opened this issue Aug 24, 2019 · 0 comments
Open

为什么Vuex的mutation中不能做异步操作? #42

GGXXMM opened this issue Aug 24, 2019 · 0 comments
Labels

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Aug 24, 2019

Vuex中 mutation 必须是同步函数。为什么呢?
异步操作不管成功或失败是不可预测的,不能立即捕获到状态。同步的意义在于每一条mutation执行后能捕获到新的状态。

mutations: {
  someMutation (state) {
    api.callAsyncMethod(() => {
      state.count++
    })
  }
}

可以想象,我们正debug一个app 并且观察 devtool 中的 mutation 日志。如上面例子,mutation写成异步函数,当 mutation 触发的时候,回调函数callAsyncMethod还没有被调用,devtools不知道什么时候回调函数被调用,不能立即捕获到新的状态。

任何在回调函数中进行的状态的改变都是不可追踪的。

参考:https://vuex.vuejs.org/zh/guide/mutations.html#mutation

@GGXXMM GGXXMM added the vue label Dec 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant