mobx-state-tree
mobx-state-tree copied to clipboard
Child models' lifecycle methods not firing until property access of node
Bug report
- [x] I've checked documentation and searched for existing issues
- [x] I've made sure my project is based on the latest MST version
- [x] Fork this code sandbox or another minimal reproduction.
Sandbox link or minimal reproduction code Sandbox Link
Potentially related to #1665.
Describe the expected behavior
The afterCreate and afterAttach hooks of the Child model should fire after the Root model creates it as part of its own tree.
Describe the observed behavior
The afterCreate and afterAttach hooks of the Child model do not fire automatically after creation/attachment by the Root model.
Of the two example Root models in the Sandbox:
Rootsimply creates aChildinstance for itschildproperty, but theafterCreate/Attachlifecycle hooks of theChilddon't fire.RootWithAccessis identical toRoothowever instead we perform a (rather useless) property accessself.childto access theChildinstance, which oddly enough flushes the seemingly pendingafterCreate/Attachlifecycle hooks. (as can be seen with console logs) — as if MST isn't flushing these pending actions until some kind of property access.
This behavior seems to be by design. More comments are in this PR: https://github.com/mobxjs/mobx-state-tree/issues/1665
I'd guess the best "fix" for this is an update to the documentation to make this more clear.
Confused how to use the undoManager since it runs into this exact issue; can't addMiddleware to root store if it doesnt exist when child is created. https://github.com/mobxjs/mobx-state-tree/blob/bac4349daa2cc2cd3e2e3516ba62f5d4ea866c27/packages/mst-middlewares/src/undo-manager.ts#L135
issue moved to : https://github.com/coolsoftwaretyler/mst-middlewares/issues/7
I think this should actually be solved with https://github.com/mobxjs/mobx-state-tree/pull/1952, but feel free to reopen if I'm incorrect on that.