MCPcopy
hub / github.com/mobxjs/mobx / makeAutoObservable

Function makeAutoObservable

packages/mobx/src/api/makeObservable.ts:51–94  ·  view source on GitHub ↗
(
    target: T,
    overrides?: AnnotationsMap<T, NoInfer<AdditionalKeys>>,
    options?: MakeObservableOptions
)

Source from the content-addressed store, hash-verified

49const keysSymbol = Symbol("mobx-keys")
50
51export function makeAutoObservable<T extends object, AdditionalKeys extends PropertyKey = never>(
52 target: T,
53 overrides?: AnnotationsMap<T, NoInfer<AdditionalKeys>>,
54 options?: MakeObservableOptions
55): T {
56 if (__DEV__) {
57 if (!isPlainObject(target) && !isPlainObject(Object.getPrototypeOf(target))) {
58 die(`'makeAutoObservable' can only be used for classes that don't have a superclass`)
59 }
60 if (isObservableObject(target)) {
61 die(`makeAutoObservable can only be used on objects not already made observable`)
62 }
63 }
64
65 // Optimization: avoid visiting protos
66 // Assumes that annotation.make_/.extend_ works the same for plain objects
67 if (isPlainObject(target)) {
68 return extendObservable(target, target, overrides, options)
69 }
70
71 initObservable(() => {
72 const adm: ObservableObjectAdministration = asObservableObject(target, options)[$mobx]
73
74 // Optimization: cache keys on proto
75 // Assumes makeAutoObservable can be called only once per object and can't be used in subclass
76 if (!target[keysSymbol]) {
77 const proto = Object.getPrototypeOf(target)
78 const keys = new Set([...ownKeys(target), ...ownKeys(proto)])
79 keys.delete("constructor")
80 keys.delete($mobx)
81 addHiddenProp(proto, keysSymbol, keys)
82 }
83
84 target[keysSymbol].forEach(key =>
85 adm.make_(
86 key,
87 // must pass "undefined" for { key: undefined }
88 !overrides ? true : key in overrides ? overrides[key] : true
89 )
90 )
91 })
92
93 return target
94}

Callers 11

become-observed.tsFile · 0.90
constructorMethod · 0.90
constructorMethod · 0.90
make-observable.tsFile · 0.90
constructorMethod · 0.90
MyClassFunction · 0.90
constructorMethod · 0.90
constructorMethod · 0.90
constructorMethod · 0.90
make-observable.jsFile · 0.85
constructorMethod · 0.85

Calls 11

dieFunction · 0.85
initObservableFunction · 0.85
ownKeysFunction · 0.85
addHiddenPropFunction · 0.85
make_Method · 0.80
extendObservableFunction · 0.70
deleteMethod · 0.65
forEachMethod · 0.65
isPlainObjectFunction · 0.50
isObservableObjectFunction · 0.50
asObservableObjectFunction · 0.50

Tested by 7

constructorMethod · 0.72
constructorMethod · 0.72
constructorMethod · 0.72
MyClassFunction · 0.72
constructorMethod · 0.72
constructorMethod · 0.72
constructorMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…