mobx-state-tree icon indicating copy to clipboard operation
mobx-state-tree copied to clipboard

Child models' lifecycle methods not firing until property access of node

Open peterboyer opened this issue 4 years ago • 1 comments

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:

  • Root simply creates a Child instance for its child property, but the afterCreate/Attach lifecycle hooks of the Child don't fire.
  • RootWithAccess is identical to Root however instead we perform a (rather useless) property access self.child to access the Child instance, which oddly enough flushes the seemingly pending afterCreate/Attach lifecycle hooks. (as can be seen with console logs) — as if MST isn't flushing these pending actions until some kind of property access.

peterboyer avatar Aug 06 '21 03:08 peterboyer

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.

scytacki avatar Aug 25 '22 18:08 scytacki

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

BrianHung avatar Aug 11 '23 07:08 BrianHung

issue moved to : https://github.com/coolsoftwaretyler/mst-middlewares/issues/7

zuhorer avatar Sep 19 '23 18:09 zuhorer

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.

coolsoftwaretyler avatar Sep 21 '23 23:09 coolsoftwaretyler