首页 > 解决方案 > VueJS/Vuex:如何处理同时发生的两个提交?

问题描述

我正在学习 VueJS 和 Vuex,并尝试使用 Vuex 商店制作一个小型管理游戏。

我店里有 100 份食物,每天,我的四个苦工需要吃 1 个单位的食物。

所以我在我的组件 Peon.vue 中观察商店的进餐时间,其中存在四个实例:

store.watch((state) => {
    if (state.time.hours === this.mealTime) {
      store.commit("mealTime");
    }
  });

在我的商店 index.js 中,提交执行以下操作:

mealTime(state) {
  state.ressources.food = {
    ...state.ressources.food,
    quantity: state.ressources.food.quantity - 1,
  }
}

我注意到当我同时有超过 1 个提交时它不起作用(想象一下 2 个 peons 都在早上 7 点吃饭?!)。它进入一个无限循环并且消息:

Maximum recursive updates exceeded. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.

我可以忘记这个问题,让他们在不同的时间吃饭,但我想在其他情况下我会遇到这个问题。

如何同时处理多个提交?我应该使用 Actions 吗?如果我应该使用动作,是否可以一个接一个地“链接”提交?

谢谢你的帮助

标签: javascriptvue.jsasynchronousvuexstore

解决方案


推荐阅读