Mobx 源码分析 - action
用法
action(fn)
action(name, fn)
@action classMethod() {}
@action(name) classMethod () {}
@action boundClassMethod = (args) => { body }
@action(name) boundClassMethod = (args) => { body }
@action.bound classMethod() {}
源码剖析
export const action: IActionFactory = function action(arg1, arg2?, arg3?, arg4?): any {
// action(fn() {})
if (arguments.length === 1 && typeof arg1 === "function")
return createAction(arg1.name || "<unnamed action>", arg1)
// action("name", fn() {})
if (arguments.length === 2 && typeof arg2 === "function") return createAction(arg1, arg2)
// @action("name") fn() {}
if (arguments.length === 1 && typeof arg1 === "string") return namedActionDecorator(arg1)
// @action fn() {}
if (arg4 === true) {
// apply to instance immediately
arg1[arg2] = createAction(arg1.name || arg2, arg3.value)
} else {
return namedActionDecorator(arg2).apply(null, arguments)
}
} as any
action.bound = boundActionDecorator as any
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
createAction
export function createAction(actionName: string, fn: Function): Function & IAction {
...
const res = function() {
return executeAction(actionName, fn, this, arguments)
}
;(res as any).isMobxAction = true
return res as any
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
createAction
返回一个函数,函数上会挂载值为 true
的 isMobxAction
属性。
executeAction
首先开启事务处理,执行传递进来的函数,并返回执行结果,最后进行事务处理,在结束事务处理阶段才会执行所有的 reaction
。