Mobx——observable 装饰器的实现原理(离职拷贝版)

离职了,把 2019 年在公司写的文档 copy 出来。年头有点久,可能写的不太对,也不是很想改了~
注:本文档对应 mobx 版本为 4.15.4、mobx-vue 版本为 2.0.10

对比 Vue 的猜想

observable 的变量对应 Vue 双向绑定的 data 数据。Vue 实现 data 的双向绑定是在 initState 中,将 data 里面的每一个变量进行递归的 defineProperty。所以猜测 observable 也是一个递归建立 get(依赖收集) & set(派发更新) 的过程

源码解析
  1. observable 函数入口
const observable: IObservableFactory & IObservableFactories & { enhancer: IEnhancer<any> } = createObservable as any

function createObservable(v: any, arg2?: any, arg3?: any) {

    // @observable someProp;
    if (typeof arguments[1] === "string") {
        return deepDecorator.apply(null, arguments as any)
    }

    // it is an observable already, done
    if (isObservable(v)) return v

    // something that can be converted and mutated?
    const res = isPlainObject(v)
        ? observable.object(v, arg2, arg3)
        : Array.isArray(v)
        ? observable.array(v, arg2)
        : isES6Map(v)
        ? observable.map(v, arg2)
        : isES6Set(v)
        ? observable.set(v, arg2)
        : v

    // this value could be converted to a new observable data structure, return it
    if (res !== v) return res
}

2.deepDecorator 装饰器入口
这里只看装饰器的用法

const deepDecorator = createDecoratorForEnhancer(deepEnhancer)

export function deepEnhancer(v, _, name) {
    // it is an observable already, done
    if (isObservable(v)) return v

    // something that can be converted and mutated?
    if (Array.isArray(v)) return observable.array(v, { name })
    if (isPlainObject(v)) return observable.object(v, undefined, { name })
    if (isES6Map(v)) return observable.map(v, { name })
    if (isES6Set(v)) return observable.set(v, { name })

    return v
}

function createDecoratorForEnhancer(enhancer: IEnhancer<any>): IObservableDecorator {
    invariant(enhancer)
    const decorator = createPropDecorator(
        true,
        (
            target: any,
            propertyName: PropertyKey,
            descriptor: BabelDescriptor | undefined,
            _decoratorTarget,
            decoratorArgs: any[]
        ) => {
            const initialValue = descriptor
                ? descriptor.initializer
                    ? descriptor.initializer.call(target)
                    : descriptor.value
                : undefined
            defineObservableProperty(target, propertyName, initialValue, enhancer)
        }
    )
    const res = ... // 就是返回一个 decorator,只不过 NODE_ENV 不是生产环境会多打一个异常的 log
    res.enhancer = enhancer
    return res
}

createDecoratorForEnhancer 中的 createPropDecorator 是核心操作,也是 Mobx 装饰器的通用核心逻辑,他的第二个入参 propertyCreator,就是将来要用来生成 get & set 逻辑的重要回调,接下来看看 createPropDecorator 的源码

  1. createPropDecorator
function createPropDecorator(
    propertyInitiallyEnumerable: boolean,
    propertyCreator: PropertyCreator
) {
    return function decoratorFactory() {
        let decoratorArguments: any[]

        const decorator = function decorate(
            target: DecoratorTarget,
            prop: string,
            descriptor: BabelDescriptor | undefined,
            applyImmediately?: any
        ) {
            if (applyImmediately === true) {
                propertyCreator(target, prop, descriptor, target, decoratorArguments)
                return null
            }
            if (process.env.NODE_ENV !== "production" && !quacksLikeADecorator(arguments))
                fail("This function is a decorator, but it wasn't invoked like a decorator")
            if (!Object.prototype.hasOwnProperty.call(target, mobxPendingDecorators)) {
                const inheritedDecorators = target.__mobxDecorators
                addHiddenProp(target, "__mobxDecorators", { ...inheritedDecorators })
            }
            target.__mobxDecorators![prop] = {
                prop,
                propertyCreator,
                descriptor,
                decoratorTarget: target,
                decoratorArguments
            }
            return createPropertyInitializerDescriptor(prop, propertyInitiallyEnumerable)
        }

        if (quacksLikeADecorator(arguments)) {
            // @decorator
            decoratorArguments = EMPTY_ARRAY
            return decorator.apply(null, arguments as any)
        } else {
            // @decorator(args)
            decoratorArguments = Array.prototype.slice.call(arguments)
            return decorator
        }
    } as Function
}

正常来说,到这一层,createPropertyInitializerDescriptor 需要 return 装饰器所需的 descriptor, 追下 createPropertyInitializerDescriptor 的源码,你会发现返回的 descriptor 并不是我们想要的那种具有依赖收集派发更新逻辑的 get 和 set,这只是一个初始化的钩子而已

  1. createPropertyInitializerDescriptor
const enumerableDescriptorCache: { [prop: string]: PropertyDescriptor } = {}
const nonEnumerableDescriptorCache: { [prop: string]: PropertyDescriptor } = {}

function createPropertyInitializerDescriptor(
    prop: string,
    enumerable: boolean
): PropertyDescriptor {
    const cache = enumerable ? enumerableDescriptorCache : nonEnumerableDescriptorCache
    return ( // 这里确实就是 createObservable 的最终返回值
        cache[prop] ||
        (cache[prop] = {
            configurable: true,
            enumerable: enumerable,
            get() {
                initializeInstance(this)
                return this[prop]
            },
            set(value) {
                initializeInstance(this)
                this[prop] = value
            }
        })
    )
}
  1. initializeInstance
function initializeInstance(target: any)
function initializeInstance(target: DecoratorTarget) {
    if (target.__mobxDidRunLazyInitializers === true) return
    const decorators = target.__mobxDecorators
    if (decorators) {
        addHiddenProp(target, "__mobxDidRunLazyInitializers", true)
        for (let key in decorators) {
            const d = decorators[key]
            d.propertyCreator(target, d.prop, d.descriptor, d.decoratorTarget, d.decoratorArguments)
        }
    }
}

这里的 decorators,也就是 target.__mobxDecorators, 是在 createPropDecorator 环节塞进去的 propertyCreator 的相关变量,在这里进行遍历调用,最终会执行每个 decorators 的 defineObservableProperty(target, propertyName, initialValue, enhancer) 语句

  1. defineObservableProperty
    其实是遍历 decorators 时 propertyCreator 内的 defineObservableProperty 操作
function defineObservableProperty(
    target: any,
    propName: string,
    newValue,
    enhancer: IEnhancer<any>
) {
    /**
    * asObservableObject 的 作用是在 类上增加了 $mobx 字段
    * 给 $mobx 字段赋值并 return 一个 new ObservableObjectAdministration(target, name, defaultEnhancer)
    */
    const adm = asObservableObject(target)
    assertPropertyConfigurable(target, propName)


    if (hasInterceptors(adm)) {
        const change = interceptChange<IObjectWillChange>(adm, {
            object: target,
            name: propName,
            type: "add",
            newValue
        })
        if (!change) return
        newValue = (change as any).newValue
    }
    
    // 然后在 ObservableObjectAdministration 的 value 上挂 ObservableValue
    const observable = (adm.values[propName] = new ObservableValue(
        newValue,
        enhancer,
        `${adm.name}.${propName}`,
        false
    ))
    newValue = (observable as any).value // observableValue might have changed it

    // 核心逻辑
    Object.defineProperty(target, propName, generateObservablePropConfig(propName))
    if (adm.keys) adm.keys.push(propName)
    notifyPropertyAddition(adm, target, propName, newValue)
}
  1. generateObservablePropConfig
function generateObservablePropConfig(propName) {
    return (
        observablePropertyConfigs[propName] ||
        (observablePropertyConfigs[propName] = {
            configurable: true,
            enumerable: true,
            get() {
                return this.$mobx.read(this, propName)
            },
            set(v) {
                this.$mobx.write(this, propName, v)
            }
        })
    )
}

this.$mobx 就是上面的那个 adm 即 new ObservableObjectAdministration,依赖收集发生在this.$mobx.read,而派发更新则是在 this.$mobx.write,Mobx 具体的依赖收集和派发更新的逻辑会在 derivation 的依赖收集过程 和 derivation 的派发更新过程 中讲解

结论

其实绕了一圈,observable装饰器大致就干了这么一件事情?

function observable(target:any, argument?:any): any {
    return {
        configurable: true,
        enumerable: true,
        get() {
            ...
        },
        set(v: any) {
            ... // 其他核心操作
            Object.defineProperty(this, argument, {
                configurable: true,
                enumerable: true,
                get() {
                    ...
                },
                set(v: any) {
                    ...
                }
            })
            ...
        }
    }
}

说下我个人的关注点:

  1. enhancer 是之前说的 deepEnhancer ,也就是对不同类型的各种 observe 的递归加工操作,初始化的时候会触发,set 一个新 value 的时候也会触发,如果你 @observable 的变量是个 string 或者 number,你会发现 deepEnhancer 是覆盖不到的,会直接 return ,observable 的函数式调用直接传进去一个 number 也会报错,提示你使用 observable.box 来进行对应的操作。本来关注 deepEnhancer 是想看看装饰器的代码和函数的代码是不是有比较高程度的复用,除了都在 deepEnhancer 以外,大流程基本是不太一样的
  2. 最终 descriptor 里的 this.$mobx 指的是 ObservableObjectAdministration ,他的 get 是返回 value 上对应响应式变量的值、而 set 则是改变这个值,和一系列响应。所有的变量都会在 ObservableObjectAdministration 一个名为 values 的 对象上:例如 value => ObservableValue;其中 ObservableValue: {key: value, value extends Atom}
  3. 通过 装饰器 和 函数 创建的 observable ,虽然都是靠 this.$mobx 即 ObservableObjectAdministration 的 read 和 write 来进行依赖收集和派发更新的,但是 @observable 的操作入口,挂在 ObservableObjectAdministration.value 上面, observable() 则是通过注入的 adm 也就是 ObservableObjectAdministration 实例, 来进行相应的操作。但是 @observable 如果是一个受 deepEnhancer 影响的引用类型,其成员都是走的 observable() 逻辑
  4. 因为项目使用 mobx4,而 demo 使用了 mobx5,期间对比了 mobx4 和 mobx5 里 @observable 的源码,主要的区别就是:
    a. 在 4版本 里面 $mobx 就是 $mobx 的字符串, 5版本则是个 Symbol
    b. this.$mobx 的 value 4 版本里是一个是对象, 5 版本是 Map
    c. 上述源码解析的第 6 步的执行的操作不一样,5 对应的操作是 asObservableObject(target).addObservableProp(propertyName, initialValue, enhancer),但是原理是一样的,都是 new 一个 ObservableObjectAdministration,然后往他的 value 上挂 ObservableValue,然后执行 Object.defineProperty,其中 descriptor 参数是通过 generateObservablePropConfig 返回的
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,012评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,589评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,819评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,652评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,954评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,381评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,687评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,404评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,082评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,355评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,880评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,249评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,864评论 3 232
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,007评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,760评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,394评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,281评论 2 259

推荐阅读更多精彩内容