Why should MobX not be used as a State Container?

2019-07-31 03:09发布

问题:

Why should MobX not be used as a State Container? as mentioned in the official docs "MobX is not a state container"? Isn't is like Redux?

回答1:

Redux is better compared with MobX State Tree I, considering the similar action dispatch pattern, tooling etc. MobX does not provide any restrictions on how new states can be derived from old ones. It's more of a Data flow library as its creator likes to call it.

MobX helps us set up Reactivity outside React components. This way view components can be kept free of logic. But it is MST that truly makes state management easier and realistically doable. It also provides devtools like Redux thanks to the introduction of types in the state. So MST would qualify as an alternative to Redux better than MobX.

Check the original post on why MobX State tree was created and how it complements MobX as a complete state management tool.



回答2:

The docs don't say that you "should not use mobx as a state container".
What they say is that "mobx is not a state container".

It's different.

Mobx is a tool that lets you write code following the observer pattern.
In the case of mobx, it's about observing and reacting upon changes in values. (another lib like rxjs use streams) Thus, the question of mobx is about whether you think that using an observer pattern will be good for you or not.

What the docs try to explain is that you can use mobx to write your app state as an observable data structure, if you want. But it won't force or help you architecture your application state in any way. I guess most people are thinking within the context of single page React apps. In the case of a react app, it's far easier to have optimized React UI components by default just by decorating them with mobx-react observer. That's an advantage of using this pattern thanks to mobx.

But its use case is not limited to create an observable app state, there are other "things" or cases that you want to "observe" in a system.

That said, when I worked on Redux/React app I haven't seen any less freedom than with mobx. Over time, best practices and tools have emerged to guide people and the Redux ecosystem seems to tackle various aspects of building an app. It's just that Redux was meant to create a representation of an app state right from the beginning. As explained in the other answer, mobx-state-tree would be more the equivalent of it.