Actions vs Mutations in VueX

When I first came across VueX, my head was left spinning for a few days. As if the whole idea of a store that had Getters and Mutations wasn’t enough, I came to know that there exists something called Actions as well. And actions do pretty much what mutations do: change state. Except that actions issued mutations and were called (“dispatched”) by components.

So, components dispatch actions to change the application state, which in turn call mutations to change the application state . . . ??

Once I dug a little deeper, I was offered another explanation: the differentiation exists because mutations can’t have asynchronous operations; for that, we have actions.

But here’s the problem: you can write asynchronous code inside mutations and it works fine. After all, it’s all just JavaScript functions. And you can have only synchronous methods inside actions, reversing the usage but effectively making no change.

What’s the big deal, then? Why care about this different, and more importantly, why follow it?

Turns out it’s an important question, and made it to the Vue.js issues list. The final explanation was provided by the creator of Vue.js himself. Here’s what Evan You says:

The whole point of a system like vuex is so that every state mutation is trackable. This is why mutations have to be sync.

Imagine you have only actions and you do this:

export function doSomething (store) {
    store.state.count++ // this can be tracked when this method is called
    api.callAsyncMethod(()) {
        store.state.count++ // this cannot, because it's async
    })
}

If you use the logger, you will see doSomething is called, but there will be additional, async state mutations happening afterwards, and when you app gets complex you will have no idea where that mutation came from. This is particularly hard to reason about when calling multiple actions with async mutations, because they can be intertwined!

Actions vs. mutations is all about separating asynchronicity from actual mutations. When you see a sync mutation in the log, you know all the side effects it can ever produce is the different between the before state and after state. But for actions, there’s no such guarantee.

So, the big deal is that Actions/Mutations form a design pattern of sorts. You are definitely not forced to follow it, but if you do, you will have a longer life. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *