MobX API 参考
¥MobX API Reference
标有 {🚀} 的功能被认为是高级功能,通常不需要。考虑下载我们方便的备忘单,它在一个页面上解释了所有重要的 API:
¥Functions marked with {🚀} are considered advanced, and should typically not be needed. Consider downloading our handy cheat sheet that explains all important APIs on a single page:
核心 API
¥Core APIs
这些是最重要的 MobX API。
¥These are the most important MobX APIs.
了解
observable
、computed
、reaction
和action
足以在你的应用中掌握和使用 MobX!¥Understanding
observable
,computed
,reaction
andaction
is enough to master and use MobX in your applications!
创建可观察量
¥Creating observables
让事物变得可观察。
¥Making things observable.
makeObservable
用法:makeObservable(target, annotations?, options?)
<小>(更多信息)</小>
¥Usage: makeObservable(target, annotations?, options?)
(further information)
属性、整个对象、数组、映射和集合都可以被观察。
¥Properties, entire objects, arrays, Maps and Sets can all be made observable.
makeAutoObservable
用法:makeAutoObservable(target, overrides?, options?)
<小>(更多信息)</小>
¥Usage: makeAutoObservable(target, overrides?, options?)
(further information)
自动使属性、对象、数组、映射和集合可观察。
¥Automatically make properties, objects, arrays, Maps and Sets observable.
extendObservable
{🚀} 用法:extendObservable(target, properties, overrides?, options?)
¥{🚀} Usage: extendObservable(target, properties, overrides?, options?)
可用于在 target
对象上引入新属性并使其立即可观察。基本上是 Object.assign(target, properties); makeAutoObservable(target, overrides, options);
的简写。但是,target
上的现有属性不会受到影响。
¥Can be used to introduce new properties on the target
object and make them observable immediately. Basically a shorthand for Object.assign(target, properties); makeAutoObservable(target, overrides, options);
. However, existing properties on target
won't be touched.
老式的构造函数可以很好地利用 extendObservable
:
¥Old-fashioned constructor functions can nicely leverage extendObservable
:
function Person(firstName, lastName) {
extendObservable(this, { firstName, lastName })
}
const person = new Person("Michel", "Weststrate")
可以使用 extendObservable
在实例化后向现有对象添加可观察字段,但请注意,以这种方式添加可观察属性本身并不是一个可以观察到的事实。
¥It is possible to use extendObservable
to add observable fields to an existing object after instantiation, but be careful that adding an observable property this way is in itself not a fact that can be observed.
observable
用法:observable(source, overrides?, options?)
、observable
(注释)或 @observable accessor
(字段装饰器)。<小>(更多信息)</小>
¥Usage: observable(source, overrides?, options?)
, observable
(annotation) or @observable accessor
(field decorator). (further information)
克隆一个对象并使其可观察。源可以是普通对象、数组、Map 或 Set。默认情况下,observable
是递归应用的。如果遇到的值之一是对象或数组,则该值也将通过 observable
传递。
¥Clones an object and makes it observable. Source can be a plain object, array, Map or Set. By default, observable
is applied recursively. If one of the encountered values is an object or array, that value will be passed through observable
as well.
observable.object
{🚀} 用法:observable.object(source, overrides?, options?)
<小>(更多信息)</小>
¥{🚀} Usage: observable.object(source, overrides?, options?)
(further information)
observable(source, overrides?, options?)
的别名。创建所提供对象的克隆并使其所有属性可观察。
¥Alias for observable(source, overrides?, options?)
. Creates a clone of the provided object and makes all of its properties observable.
observable.array
{🚀} 用法:observable.array(initialValues?, options?)
¥{🚀} Usage: observable.array(initialValues?, options?)
基于提供的 initialValues
创建一个新的可观察数组。要将可观察数组转换回普通数组,请使用 .slice()
方法,或查看 至 JS 以递归方式转换它们。除了所有语言内置数组函数之外,可观察数组还提供以下功能:
¥Creates a new observable array based on the provided initialValues
.
To convert observable arrays back to plain arrays, use the .slice()
method, or check out toJS to convert them recursively.
Besides all the language built-in array functions, the following goodies are available on observable arrays as well:
clear()
从数组中删除所有当前条目。¥
clear()
removes all current entries from the array.replace(newItems)
将数组中的所有现有条目替换为新条目。¥
replace(newItems)
replaces all existing entries in the array with new ones.remove(value)
按值从数组中删除单个项目,如果找到并删除该项目,则返回true
。¥
remove(value)
removes a single item by value from the array and returnstrue
if the item was found and removed.
如果数组中的值不应自动转换为可观察值,请使用 { deep: false }
选项使数组浅可观察。
¥If the values in the array should not be turned into observables automatically, use the { deep: false }
option to make the array shallowly observable.
observable.map
{🚀} 用法:observable.map(initialMap?, options?)
¥{🚀} Usage: observable.map(initialMap?, options?)
基于提供的 initialMap
创建一个新的可观察的 ES6 Map。如果你不仅想对特定条目的更改做出反应,而且还想对它们的添加和删除做出反应,那么它们非常有用。如果你没有 启用代理,则创建可观察映射是创建动态键控集合的推荐方法。
¥Creates a new observable ES6 Map based on the provided initialMap
.
They are very useful if you don't want to react just to the change of a specific entry, but also to their addition and removal.
Creating observable Maps is the recommended approach for creating dynamically keyed collections if you don't have enabled Proxies.
除了所有语言内置的 Map 函数之外,可观察的 Map 还提供以下功能:
¥Besides all the language built-in Map functions, the following goodies are available on observable Maps as well:
toJSON()
返回此 Map 的浅层普通对象表示(使用 至 JS 进行深层复制)。¥
toJSON()
returns a shallow plain object representation of this Map (use toJS for a deep copy).merge(values)
将提供的values
(普通对象、条目数组或字符串键控 ES6 Map)中的所有条目复制到此 Map 中。¥
merge(values)
copies all entries from the providedvalues
(plain object, array of entries or a string-keyed ES6 Map) into this Map.replace(values)
用提供的values
替换了该映射的全部内容。¥
replace(values)
replaces the entire contents of this Map with the providedvalues
.
如果 Map 中的值不应自动转换为可观察值,请使用 { deep: false }
选项使 Map 浅可观察。
¥If the values in the Map should not be turned into observables automatically, use the { deep: false }
option to make the Map shallowly observable.
observable.set
{🚀} 用法:observable.set(initialSet?, options?)
¥{🚀} Usage: observable.set(initialSet?, options?)
基于提供的 initialSet
创建一个新的可观察的 ES6 Set。每当你想要创建动态集(其中需要观察值的添加和删除,但值在整个集合中只能出现一次)时,请使用它。
¥Creates a new observable ES6 Set based on the provided initialSet
. Use it whenever you want to create a dynamic set where the addition and removal of values needs to be observed, but where values can appear only once in the entire collection.
如果 Set 中的值不应自动转换为可观察值,请使用 { deep: false }
选项使 Set 浅可观察。
¥If the values in the Set should not be turned into observables automatically, use the { deep: false }
option to make the Set shallowly observable.
与 Map 键不同,Set 值为 不单独追踪。
¥Unlike Map keys, Set values are not tracked individually.
observable.ref
用法:observable.ref
(注解)(更多信息)
¥Usage: observable.ref
(annotation) (further information)
与 observable
注释类似,但只会跟踪重新分配。分配的值本身不会自动变得可观察。例如,如果你打算将不可变数据存储在可观察字段中,请使用此选项。
¥Like the observable
annotation, but only reassignments will be tracked. The assigned values themselves won't be made observable automatically. For example, use this if you intend to store immutable data in an observable field.
observable.shallow
用法:observable.shallow
(注解)(更多信息)
¥Usage: observable.shallow
(annotation) (further information)
与 observable.ref
注释类似,但用于集合。分配的任何集合都将变得可观察,但集合本身的内容不会变得可观察。
¥Like the observable.ref
annotation, but for collections. Any collection assigned will be made observable, but the contents of the collection itself won't become observable.
observable.struct
{🚀} 用法:observable.struct
(注解)(更多信息)
¥{🚀} Usage: observable.struct
(annotation) (further information)
与 observable
注释类似,但结构上等于当前值的任何指定值都将被忽略。
¥Like the observable
annotation, except that any assigned value that is structurally equal to the current value will be ignored.
observable.deep
{🚀} 用法:observable.deep
(注解)(更多信息)
¥{🚀} Usage: observable.deep
(annotation) (further information)
observable
注释的别名。
¥Alias for the observable
annotation.
observable.box
{🚀} 用法:observable.box(value, options?)
¥{🚀} Usage: observable.box(value, options?)
JavaScript 中的所有原始值都是不可变的,因此根据定义是不可观察的。通常这很好,因为 MobX 可以使包含该值的属性可观察。在极少数情况下,拥有不属于对象的可观察原语会很方便。对于这种情况,可以创建一个可观察的盒子来管理这样的原语。
¥All primitive values in JavaScript are immutable and hence per definition not observable. Usually that is fine, as MobX can just make the property that contains the value observable. In rare cases, it can be convenient to have an observable primitive that is not owned by an object. For such cases, it is possible to create an observable box that manages such a primitive.
observable.box(value)
接受任何值并将其存储在一个框中。当前值可以通过 .get()
访问并使用 .set(newValue)
更新。
¥observable.box(value)
accepts any value and stores it inside a box. The current value can be accessed through .get()
and updated using .set(newValue)
.
import { observable, autorun } from "mobx"
const cityName = observable.box("Vienna")
autorun(() => {
console.log(cityName.get())
})
// Prints: 'Vienna'
cityName.set("Amsterdam")
// Prints: 'Amsterdam'
如果框中的值不应自动转换为可观察值,请使用 { deep: false }
选项使框浅可观察。
¥If the values in the box should not be turned into observables automatically, use the { deep: false }
option to make the box shallowly observable.
操作
¥Actions
操作是修改状态的任何代码段。
¥An action is any piece of code that modifies the state.
action
用法:action(fn)
、action
(注释)或 @action
(方法/字段装饰器)(更多信息)
¥Usage: action(fn)
, action
(annotation) or @action
(method / field decorator) (further information)
用于打算修改状态的函数。
¥Use on functions that intend to modify the state.
runInAction
{🚀} 用法:runInAction(fn)
<小>(更多信息)</小>
¥{🚀} Usage: runInAction(fn)
(further information)
创建立即调用的一次性操作。
¥Create a one-time action that is immediately invoked.
flow
用法:flow(fn)
、flow
(注解)或 @flow
(生成器方法装饰器)(更多信息)
¥Usage: flow(fn)
, flow
(annotation) or @flow
(generator method decorator) (further information)
MobX 友好地替代 async
/ await
,支持取消。
¥MobX friendly replacement for async
/ await
that supports cancellation.
flowResult
用法:flowResult(flowFunctionResult)
<小>(更多信息)</小>
¥Usage: flowResult(flowFunctionResult)
(further information)
仅适用于 TypeScript 用户。将生成器的输出转换为 promise 的实用程序。这只是对 flow
完成的 promise 封装的类型修复。运行时它直接返回输入的值。
¥For TypeScript users only. Utility that casts the output of the generator to a promise.
This is just a type-wise correction for the promise wrapping done by flow
. At runtime it directly returns the inputted value.
计算
¥Computeds
计算值可用于从其他可观测值中获取信息。
¥Computed values can be used to derive information from other observables.
computed
用法:computed(fn, options?)
、computed(options?)
(注解)或 @computed
(getter 装饰器)(更多信息)
¥Usage: computed(fn, options?)
, computed(options?)
(annotation) or @computed
(getter decorator) (further information)
创建一个从其他可观察值派生的可观察值,但除非底层可观察值之一发生更改,否则不会重新计算。
¥Creates an observable value that is derived from other observables, but won't be recomputed unless one of the underlying observables changes.
React 集成
¥React integration
来自 mobx-react
/ mobx-react-lite
包。
¥From the mobx-react
/ mobx-react-lite
packages.
observer
用法:observer(component)
<小>(更多信息)</小>
¥Usage: observer(component)
(further information)
一个高阶组件,可用于在可观察值更改时重新渲染基于函数或类的 React 组件。
¥A higher order component you can use to make a functional or class based React component re-render when observables change.
Observer
用法:<Observer>{() => rendering}</Observer>
<小>(更多信息)</小>
¥Usage: <Observer>{() => rendering}</Observer>
(further information)
渲染给定的渲染函数,并在渲染函数中使用的可观察值之一发生更改时自动重新渲染它。
¥Renders the given render function, and automatically re-renders it once one of the observables used in the render function changes.
useLocalObservable
用法:useLocalObservable(() => source, annotations?)
<小>(更多信息)</小>
¥Usage: useLocalObservable(() => source, annotations?)
(further information)
使用 makeObservable
创建一个新的可观察对象,并在组件的整个生命周期中将其保留在组件中。
¥Creates a new observable object using makeObservable
, and keeps it around in the component for the entire life-cycle of the component.
反应
¥Reactions
反应的目标是对自动发生的副作用进行建模。
¥The goal of reactions is to model side effects that happen automatically.
autorun
用法:autorun(() => effect, options?)
<小>(更多信息)</小>
¥Usage: autorun(() => effect, options?)
(further information)
每次观察到任何变化时都会重新运行函数。
¥Reruns a function every time anything it observes changes.
reaction
用法:reaction(() => data, data => effect, options?)
<小>(更多信息)</小>
¥Usage: reaction(() => data, data => effect, options?)
(further information)
当任何选定的数据发生更改时,重新运行副作用。
¥Reruns a side effect when any selected data changes.
when
用法:when(() => condition, () => effect, options?)
或 await when(() => condition, options?)
<小>(更多信息)</小>
¥Usage: when(() => condition, () => effect, options?)
or await when(() => condition, options?)
(further information)
当可观察条件成立时执行一次副作用。
¥Executes a side effect once when a observable condition becomes true.
实用工具
¥Utilities
可以使处理可观察对象或计算值更加方便的实用程序。mobx-utils 包中还可以找到一些不那么简单的实用程序。
¥Utilities that might make working with observable objects or computed values more convenient. Less trivial utilities can also be found in the mobx-utils package.
onReactionError
{🚀} 用法:onReactionError(handler: (error: any, derivation) => void)
¥{🚀} Usage: onReactionError(handler: (error: any, derivation) => void)
附加一个全局错误监听器,为响应引发的每个错误调用该监听器。这可用于监控或测试目的。
¥Attaches a global error listener, which is invoked for every error that is thrown from a reaction. This can be used for monitoring or test purposes.
intercept
{🚀} 用法:intercept(propertyName|array|object|Set|Map, listener)
<小>(更多信息)</小>
¥{🚀} Usage: intercept(propertyName|array|object|Set|Map, listener)
(further information)
在将更改应用于可观察的 API 之前拦截更改。返回一个停止拦截的处理函数。
¥Intercepts changes before they are applied to an observable API. Returns a disposer function that stops the interception.
observe
{🚀} 用法:observe(propertyName|array|object|Set|Map, listener)
<小>(更多信息)</小>
¥{🚀} Usage: observe(propertyName|array|object|Set|Map, listener)
(further information)
可用于观察单个可观察值的底层 API。返回一个停止拦截的处理函数。
¥Low-level API that can be used to observe a single observable value. Returns a disposer function that stops the interception.
onBecomeObserved
{🚀} 用法:onBecomeObserved(observable, property?, listener: () => void)
<小>(更多信息)</小>
¥{🚀} Usage: onBecomeObserved(observable, property?, listener: () => void)
(further information)
当某件事被观察到时钩子。
¥Hook for when something becomes observed.
onBecomeUnobserved
{🚀} 用法:onBecomeUnobserved(observable, property?, listener: () => void)
<小>(更多信息)</小>
¥{🚀} Usage: onBecomeUnobserved(observable, property?, listener: () => void)
(further information)
当某件事不再被观察时钩子。
¥Hook for when something stops being observed.
toJS
用法:toJS(value)
<小>(更多信息)</小>
¥Usage: toJS(value)
(further information)
递归地将可观察对象转换为 JavaScript 对象。支持可观察数组、对象、映射和基元。
¥Recursively converts an observable object to a JavaScript object. Supports observable arrays, objects, Maps and primitives.
它不会递归为不可观察量,它们会保持原样,即使它们包含可观察量。计算属性和其他不可枚举属性将被完全忽略并且不会返回。
¥It does NOT recurse into non-observables, these are left as they are, even if they contain observables. Computed and other non-enumerable properties are completely ignored and won't be returned.
对于更复杂的(反)序列化场景,建议为类提供(计算的)toJSON
方法,或使用像 serializr 这样的序列化库。
¥For more complex (de)serialization scenarios, it is recommended to give classes a (computed) toJSON
method, or use a serialization library like serializr.
const obj = mobx.observable({
x: 1
})
const clone = mobx.toJS(obj)
console.log(mobx.isObservableObject(obj)) // true
console.log(mobx.isObservableObject(clone)) // false
配置
¥Configuration
微调你的 MobX 实例。
¥Fine-tuning your MobX instance.
configure
用法:设置活动 MobX 实例上的全局行为设置。(更多信息) 用它来改变 MobX 的整体行为方式。
¥Usage: sets global behavior settings on the active MobX instance. (further information) Use it to change how MobX behaves as a whole.
集合实用程序 {🚀}
¥Collection utilities {🚀}
它们可以使用相同的通用 API 来操作可观察的数组、对象和映射。这在 没有 Proxy
支持的环境 中很有用,但通常不需要。
¥They enable manipulating observable arrays, objects and Maps with the same generic API. This can be useful in environments without Proxy
support, but is otherwise typically not needed.
values
{🚀} 用法:values(array|object|Set|Map)
<小>(更多信息)</小>
¥{🚀} Usage: values(array|object|Set|Map)
(further information)
以数组形式返回集合中的所有值。
¥Returns all values in the collection as an array.
keys
{🚀} 用法:keys(array|object|Set|Map)
<小>(更多信息)</小>
¥{🚀} Usage: keys(array|object|Set|Map)
(further information)
以数组形式返回集合中的所有键/索引。
¥Returns all keys / indices in the collection as an array.
entries
{🚀} 用法:entries(array|object|Set|Map)
<小>(更多信息)</小>
¥{🚀} Usage: entries(array|object|Set|Map)
(further information)
以数组形式返回集合中每个条目的 [key, value]
对。
¥Returns a [key, value]
pair of every entry in the collection as an array.
set
{🚀} 用法:set(array|object|Map, key, value)
<小>(更多信息)</小>
¥{🚀} Usage: set(array|object|Map, key, value)
(further information)
更新集合。
¥Updates the collection.
remove
{🚀} 用法:remove(array|object|Map, key)
<小>(更多信息)</小>
¥{🚀} Usage: remove(array|object|Map, key)
(further information)
从集合中删除项目。
¥Removes item from the collection.
has
{🚀} 用法:has(array|object|Map, key)
<小>(更多信息)</小>
¥{🚀} Usage: has(array|object|Map, key)
(further information)
检查集合中的成员资格。
¥Checks for membership in the collection.
get
{🚀} 用法:get(array|object|Map, key)
<小>(更多信息)</小>
¥{🚀} Usage: get(array|object|Map, key)
(further information)
使用 key 从集合中获取值。
¥Gets value from the collection with key.
自省实用程序 {🚀}
¥Introspection utilities {🚀}
如果你想要检查 MobX 的内部状态,或者想要在 MobX 之上构建很酷的工具,这些实用程序可能会派上用场。
¥Utilities that might come in handy if you want to inspect the internal state of MobX, or want to build cool tools on top of MobX.
isObservable
{🚀} 用法:isObservable(array|object|Set|Map)
¥{🚀} Usage: isObservable(array|object|Set|Map)
MobX 可以观察对象/集合吗?
¥Is the object / collection made observable by MobX?
isObservableProp
{🚀} 用法:isObservableProp(object, propertyName)
¥{🚀} Usage: isObservableProp(object, propertyName)
属性是可观察的吗?
¥Is the property observable?
isObservableArray
{🚀} 用法:isObservableArray(array)
¥{🚀} Usage: isObservableArray(array)
该值是可观察的数组吗?
¥Is the value an observable array?
isObservableObject
{🚀} 用法:isObservableObject(object)
¥{🚀} Usage: isObservableObject(object)
该值是可观察的对象吗?
¥Is the value an observable object?
isObservableSet
{🚀} 用法:isObservableSet(set)
¥{🚀} Usage: isObservableSet(set)
该值是可观察的集合吗?
¥Is the value an observable Set?
isObservableMap
{🚀} 用法:isObservableMap(map)
¥{🚀} Usage: isObservableMap(map)
该值是可观察的 Map 吗?
¥Is the value an observable Map?
isBoxedObservable
{🚀} 用法:isBoxedObservable(value)
¥{🚀} Usage: isBoxedObservable(value)
该值是使用 observable.box
创建的可观察框吗?
¥Is the value an observable box, created using observable.box
?
isAction
{🚀} 用法:isAction(func)
¥{🚀} Usage: isAction(func)
该函数是否标记为 action
?
¥Is the function marked as an action
?
isComputed
{🚀} 用法:isComputed(boxedComputed)
¥{🚀} Usage: isComputed(boxedComputed)
这是使用 computed(() => expr)
创建的装箱计算值吗?
¥Is this a boxed computed value, created using computed(() => expr)
?
isComputedProp
{🚀} 用法:isComputedProp(object, propertyName)
¥{🚀} Usage: isComputedProp(object, propertyName)
这是计算属性吗?
¥Is this a computed property?
trace
{🚀} 用法:trace()
、trace(true)
(输入调试器)或 trace(object, propertyName, enterDebugger?)
(更多信息)
¥{🚀} Usage: trace()
, trace(true)
(enter debugger) or trace(object, propertyName, enterDebugger?)
(further information)
应该在观察者、反应或计算值内部使用。当值无效时记录,或者如果使用 true 调用则设置调试器断点。
¥Should be used inside an observer, reaction or computed value. Logs when the value is invalidated, or sets the debugger breakpoint if called with true.
spy
{🚀} 用法:spy(eventListener)
<小>(更多信息)</小>
¥{🚀} Usage: spy(eventListener)
(further information)
注册一个全局间谍监听器,用于监听 MobX 中发生的所有事件。
¥Registers a global spy listener that listens to all events that happen in MobX.
getDebugName
{🚀} 用法:getDebugName(reaction|array|Set|Map)
或 getDebugName(object|Map, propertyName)
<小>(更多信息)</小>
¥{🚀} Usage: getDebugName(reaction|array|Set|Map)
or getDebugName(object|Map, propertyName)
(further information)
返回可观察或反应的(生成的)友好调试名称。
¥Returns the (generated) friendly debug name for an observable or reaction.
getDependencyTree
{🚀} 用法:getDependencyTree(object, computedPropertyName)
<小>(更多信息)</小>
¥{🚀} Usage: getDependencyTree(object, computedPropertyName)
(further information)
返回一个树结构,其中包含给定反应/计算当前依赖的所有可观察值。
¥Returns a tree structure with all observables the given reaction / computation currently depends upon.
getObserverTree
{🚀} 用法:getObserverTree(array|Set|Map)
或 getObserverTree(object|Map, propertyName)
<小>(更多信息)</小>
¥{🚀} Usage: getObserverTree(array|Set|Map)
or getObserverTree(object|Map, propertyName)
(further information)
返回一个树结构,其中包含观察给定可观察量的所有反应/计算。
¥Returns a tree structure with all reactions / computations that are observing the given observable.
扩展 MobX {🚀}
¥Extending MobX {🚀}
在极少数情况下,你想要扩展 MobX 本身。
¥In the rare case you want to extend MobX itself.
createAtom
{🚀} 用法:createAtom(name, onBecomeObserved?, onBecomeUnobserved?)
<小>(更多信息)</小>
¥{🚀} Usage: createAtom(name, onBecomeObserved?, onBecomeUnobserved?)
(further information)
创建你自己的可观察数据结构并将其连接到 MobX。由所有可观察数据类型在内部使用。Atom 公开了两种报告方法来通知 MobX:
¥Creates your own observable data structure and hooks it up to MobX. Used internally by all observable data types. Atom exposes two report methods to notify MobX with when:
reportObserved()
:该原子已被观察到,并且应被视为当前派生的依赖树的一部分。¥
reportObserved()
: the atom has become observed, and should be considered part of the dependency tree of the current derivation.reportChanged()
:原子已经改变,所有依赖于它的推导都应该失效。¥
reportChanged()
: the atom has changed, and all derivations depending on it should be invalidated.
getAtom
{🚀} 用法:getAtom(thing, property?)
<小>(更多信息)</小>
¥{🚀} Usage: getAtom(thing, property?)
(further information)
返回支持原子。
¥Returns the backing atom.
transaction
{🚀} 用法:transaction(worker: () => any)
¥{🚀} Usage: transaction(worker: () => any)
事务是一个底层 API。建议使用 action
或 runInAction
代替。
¥Transaction is a low-level API. It is recommended to use action
or runInAction
instead.
用于批处理一堆更新,直到事务结束为止不运行任何反应。与 untracked
一样,它由 action
自动应用,因此通常使用操作比直接使用 transaction
更有意义。
¥Used to batch a bunch of updates without running any reactions until the end of the transaction. Like untracked
, it is automatically applied by action
, so usually it makes more sense to use actions than to use transaction
directly.
它采用单个无参数 worker
函数作为参数,并返回它返回的任何值。请注意,transaction
完全同步运行并且可以嵌套。只有完成最外面的 transaction
后,挂起的反应才会运行。
¥It takes a single, parameterless worker
function as an argument, and returns any value that was returned by it.
Note that transaction
runs completely synchronously and can be nested. Only after completing the outermost transaction
, the pending reactions will be run.
import { observable, transaction, autorun } from "mobx"
const numbers = observable([])
autorun(() => console.log(numbers.length, "numbers!"))
// Prints: '0 numbers!'
transaction(() => {
transaction(() => {
numbers.push(1)
numbers.push(2)
})
numbers.push(3)
})
// Prints: '3 numbers!'
untracked
{🚀} 用法:untracked(worker: () => any)
¥{🚀} Usage: untracked(worker: () => any)
Untracked 是一个底层 API。建议使用 reaction
、action
或 runInAction
代替。
¥Untracked is a low-level API. It is recommended to use reaction
, action
or runInAction
instead.
运行一段代码而不建立观察者。与 transaction
一样,untracked
是由 action
自动应用的,因此通常使用操作比直接使用 untracked
更有意义。
¥Runs a piece of code without establishing observers. Like transaction
, untracked
is automatically applied by action
, so usually it makes more sense to use actions than to use untracked
directly.
const person = observable({
firstName: "Michel",
lastName: "Weststrate"
})
autorun(() => {
console.log(
person.lastName,
",",
// This untracked block will return the person's
// firstName without establishing a dependency.
untracked(() => person.firstName)
)
})
// Prints: 'Weststrate, Michel'
person.firstName = "G.K."
// Doesn't print!
person.lastName = "Chesterton"
// Prints: 'Chesterton, G.K.'