background

When we used VUex for state management, we always saw that the only way to change the state in vuex store was to submit mutation. However, we could not change the value of state without mutation, which was actually wrong. We can also change the state value by using the following method.

this.$store.state.aaa = xxx
Copy the code

And we found that when we modify state directly, the state in the store can be changed, and it is responsive, and there is no error. But why does the documentation emphasize that the only way we can change state is by submitting mutation?

When we change the vuex mode to strict mode, the console will report an error when we change the state directly by changing state.

This is also described in the official documentation

To turn on strict mode, simply pass strict: true when creating a store; In strict mode, an error is thrown whenever a state change occurs that is not caused by a mutation function. This ensures that all state changes are tracked by the debugging tool.

answer

The purpose of using commit to commit state changes is to work with developer tools to make state changes better. Finally, you can save state snapshots and implement operations such as time roaming or rollback.

In fact, the official documentation explains it quite well

This simple convention makes your intentions clear, making it easier to interpret in-app state changes as you read the code. In addition, this gives us the opportunity to implement debugging tools that record every state change and save a snapshot of the state. With it, we can even implement a time-travel debugging experience.

Source code analysis

First let’s see what vuex does when we start in strict mode

“After turning on strict mode, we execute the enableStrictMode function (watch), which internally determines the update of state (if state changes), what do you think of the value of store. _research (non-production mode).

What we found is that the default value of store. _research () is false, so by default, when state changes, it will throw wrong.

Let’s look at the logic of changing state via commit

What we found is that when we do a state change with commit, we set _research to true (right) so we don’t report an error.

conclusion

According to the above analysis, when developing the mode, we had better set it to strict mode when using VUEX. When modifying the state, we should not directly modify it, but commit it through commit. The main reason is that the state can be tracked well, the developer tools can handle state changes better, and the debugging experience is better.