MobX
简单,可扩展的状态管理
文档翻译贡献者
不再支持的旧版文档链接可以在这里找到:MobX 5、MobX 4(LTS)、MobX 3。不过请务必首先阅读当前版本的文档。
Mobxjs Team 衷心感谢以下参与文档翻译的同学(排名不分先后):
Mobx 项目赞助商
MobX 因为以下赞助商和其他许多独立资助者的慷慨相助而成为可能。赞助直接影响着这个项目的长久发展。
入门
任何可以从应用状态中派生出来的东西都应该被自动派生出来。
MobX 是一个身经百战的库,它通过运用透明的函数式响应编程(Transparent Functional Reactive Programming,TFRP)使状态管理变得简单和可扩展。
简单直接
编写没有模板的极简代码来精准描述出你的意图。要更新一个记录字段?用熟悉的 JavaScript 赋值就行。要在异步进程中更新数据?不需要特殊的工具,响应性系统会侦测到你所有的变更并把它们传送到其用武之地。
轻松实现最优渲染
所有对你数据的变更和使用都会在运行时被追踪到,并构成一个对所有状态和输出之间关系进行捕捉的依赖树。这样保证了依赖于你的状态的计算只有在真正需要时才会运行,就像 React 组件一样。而不需要使用记忆化或选择器之类容易出错的次优技巧来对组件进行手动优化。
架构上的自由
MobX 不会用它自己的规则来限制你,它可以让你在任意 UI 框架之外管理你的应用状态。这样就会使你的代码低耦合、可移植和——最重要的——容易测试。
一个简单的例子
那么使用 MobX 的代码是什么样的呢?
import React from "react"
import ReactDOM from "react-dom"
import { makeAutoObservable } from "mobx"
import { observer } from "mobx-react"
// 对应用状态进行建模。
class Timer {
secondsPassed = 0
constructor() {
makeAutoObservable(this)
}
increase() {
this.secondsPassed += 1
}
reset() {
this.secondsPassed = 0
}
}
const myTimer = new Timer()
// 构建一个使用 observable 状态的“用户界面”。
const TimerView = observer(({ timer }) => (
<button onClick={() => timer.reset()}>已过秒数:{timer.secondsPassed}</button>
))
ReactDOM.render(<TimerView timer={myTimer} />, document.body)
// 每秒更新一次‘已过秒数:X’中的文本。
setInterval(() => {
myTimer.increase()
}, 1000)
The observer
wrapper around the TimerView
React component, will automatically detect that rendering
depends on the timer.secondsPassed
observable, even though this relationship is not explicitly defined. The reactivity system will take care of re-rendering the component when precisely that field is updated in the future.
Every event (onClick
/ setInterval
) invokes an action (myTimer.increase
/ myTimer.reset
) that updates observable state (myTimer.secondsPassed
).
Changes in the observable state are propagated precisely to all computations and side effects (TimerView
) that depend on the changes being made.
This conceptual picture can be applied to the above example, or any other application using MobX.
To learn about the core concepts of MobX using a larger example, check out The gist of MobX section, or take the 10 minute interactive introduction to MobX and React. The philosophy and benefits of the mental model provided by MobX are also described in great detail in the blog posts UI as an afterthought and How to decouple state and UI (a.k.a. you don’t need componentWillMount).
What others are saying...
Guise, #mobx isn't pubsub, or your grandpa's observer pattern. Nay, it is a carefully orchestrated observable dimensional portal fueled by the power cosmic. It doesn't do change detection, it's actually a level 20 psionic with soul knife, slashing your viewmodel into submission.
After using #mobx for lone projects for a few weeks, it feels awesome to introduce it to the team. Time: 1/2, Fun: 2X
Working with #mobx is basically a continuous loop of me going “this is way too simple, it definitely won’t work” only to be proven wrong
I have built big apps with MobX already and comparing to the one before that which was using Redux, it is simpler to read and much easier to reason about.
The #mobx is the way I always want things to be! It's really surprising simple and fast! Totally awesome! Don't miss it!
Further resources and documentation
- MobX cheat sheet (also sponsors the project)
- 10 minute interactive introduction to MobX and React
- Egghead.io course, based on MobX 3
The MobX book
Created by Pavan Podila and Michel Weststrate.
Videos
- Introduction to MobX & React in 2020 by Leigh Halliday, 17min.
- ReactNext 2016: Real World MobX by Michel Weststrate, 40min, slides.
- CityJS 2020: MobX, from mutable to immutable, to observable data by Michel Weststrate, 30min.
- OpenSourceNorth: Practical React with MobX (ES5) by Matt Ruby, 42min.
- HolyJS 2019: MobX and the unique symbiosis of predictability and speed by Michel Weststrate, 59min.
- React Amsterdam 2016: State Management Is Easy by Michel Weststrate, 20min, slides.
- {🚀} React Live 2019: Reinventing MobX by Max Gallo, 27min.
And an all around MobX awesome list.
Credits
MobX is inspired by reactive programming principles as found in the spreadsheets. It is inspired by MVVM frameworks like MeteorJS tracker, knockout and Vue.js, but MobX brings Transparent Functional Reactive Programming to the next level and provides a standalone implementation. It implements TFRP in a glitch-free, synchronous, predictable and efficient manner.
A ton of credits goes to Mendix, for providing the flexibility and support to maintain MobX and the chance to proof the philosophy of MobX in a real, complex, performance critical applications.