This is the 17th day of my participation in the Genwen Challenge

background

When we use Vuex for state management, we always see a sentence that the only way to change the state in vuex store is to commit the state. We can also change the state value by using the following method.

his.$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 document emphasize that the only way we can change state is to commit?

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

Once strict mode is enabled we will executeenableStrictModeDelta function, which goes through the insidewatchTo judgestateUpdate whenstateAfter the change, if the non-production mode, judgestore._committingTo see if the throw is wrong.

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.