2

I was wondering why all tutorials say that mutations cannot use async code.

I tried it and it obviously works:

mutations: {
    clearTodo(state) { setTimeout(() => state.todo = '', 1000) }
},

results in the same behaviour as:

mutations: {
    clearTodo(state) { state.todo = '' }
},
actions: {
    clearTodoAction({commit}) { setTimeout(() => commit('clearTodo'), 1000)}
}
Chris
  • 13,100
  • 23
  • 79
  • 162
  • 1
    This pattern insures predictability of changes in your state. Otherwise async calls can rewrite each others results in unpredictable order. – Egor Stambakio May 31 '17 at 09:44
  • 1
    You can have a look here(https://github.com/vuejs/vuex/issues/42) where Evan You answers why mutations should be synchronous and action asynchronous – Vamsi Krishna May 31 '17 at 09:52

1 Answers1

3

Please read the explanation on this thread

to make story short, this is the best answer in my opinion

enter image description here

LiranC
  • 2,400
  • 1
  • 27
  • 55