Vuex Action vs Mutations

前端 未结 13 1095
囚心锁ツ
囚心锁ツ 2020-12-02 04:37

In Vuex, what is the logic of having both \"actions\" and \"mutations?\"

I understand the logic of components not being able to modify state (which seems smart), but

13条回答
  •  一向
    一向 (楼主)
    2020-12-02 05:18

    Disclaimer - I've only just started using vuejs so this is just me extrapolating the design intent.

    Time machine debugging uses snapshots of the state, and shows a timeline of actions and mutations. In theory we could have had just actions alongside a recording of state setters and getters to synchronously describe mutation. But then:

    • We would have impure inputs (async results) which caused the setters and getters. This would be hard to follow logically and different async setters and getters may surprisingly interact. That can still happen with mutations transactions but then we can say the transaction needs to be improved as opposed to it being a race condition in the actions. Anonymous mutations inside an action could more easily resurface these kinds of bugs because async programming is fragile and difficult.
    • The transaction log would be hard to read because there would be no name for the state changes. It would be much more code-like and less English, missing the logical groupings of mutations.
    • It might be trickier and less performant to instrument recording any mutation on a data object, as opposed to now where there are synchronously defined diff points - before and after mutation function call. I'm not sure how big of a problem that is.

    Compare the following transaction log with named mutations.

    Action: FetchNewsStories
    Mutation: SetFetchingNewsStories
    Action: FetchNewsStories [continuation]
    Mutation: DoneFetchingNewsStories([...])
    

    With a transaction log that has no named mutations:

    Action: FetchNewsStories
    Mutation: state.isFetching = true;
    Action: FetchNewsStories [continuation]
    Mutation: state.isFetching = false;
    Mutation: state.listOfStories = [...]
    

    I hope you can extrapolate from that example the potential added complexity in async and anonymous mutation inside actions.

    https://vuex.vuejs.org/en/mutations.html

    Now imagine we are debugging the app and looking at the devtool's mutation logs. For every mutation logged, the devtool will need to capture a "before" and "after" snapshots of the state. However, the asynchronous callback inside the example mutation above makes that impossible: the callback is not called yet when the mutation is committed, and there's no way for the devtool to know when the callback will actually be called - any state mutation performed in the callback is essentially un-trackable!

提交回复
热议问题