mobxjs / mobx-state-tree

Full-featured reactive state management without the boilerplate
https://mobx-state-tree.js.org/
MIT License
6.9k stars 640 forks source link

Model constructor modifies descriptor object #2175

Closed dangreen closed 2 months ago

dangreen commented 2 months ago

Bug report

Sandbox link or minimal reproduction code

https://codesandbox.io/p/sandbox/mobx-state-tree-todolist-forked-vvgtfy

Describe the expected behavior

I see that it was perf optimization

https://github.com/mobxjs/mobx-state-tree/commit/a411fc10b50fadf120ba0991081f289140090c50#diff-8ce65433bb1651566fa2253bfc8167953b5871ef77ed073d1d47d0e4876fabdcR292

but it looks like breaking change, but it was released in minor version

Describe the observed behavior

Model constructor modifies descriptor object

const props = {
  num: 0,
  str: ''
}
const Model1 = types.model('Model1', props) // props object was modified here
console.log(props) // it's not a { num: 0, str: '' }
dangreen commented 2 months ago

@coolsoftwaretyler @jamonholmgren fyi

coolsoftwaretyler commented 2 months ago

Ah good point, @dangreen. I don't think we considered the use case where you'd want to have the original object stay un-modified. Most of the time, I think of model instantiation like:

const Model1 = types.model('Model1', { num: 0, str: ''})

In which case, the in-place modification wouldn't be a problem. I can see how you would consider this a breaking change, though we certainly didn't. It can be tough to determine the right classification for changes in MST, where there is a lot of undocumented and untested behavior.

I really prefer the changed version of this, but I wonder if we can put it behind an opt-in flag instead, to restore the prior behavior, but allow people to get the benefits of faster model instantiation when they know their second parameter is safe to modify.

I'll label this as a bug and we'll see what we can do here. Thanks for the issue, and would be happy to review a PR!

dangreen commented 2 months ago

why not just copy object before reduce it?

return keysList.reduce((props, key) => { ... }, { ...declaredProps })

Before optimization object was copied on every loop step, in that way it will be copied only once.

coolsoftwaretyler commented 2 months ago

That works, too! I was just writing my first idea, haha. I like yours better.

Do you want to open a PR to that effect?

coolsoftwaretyler commented 2 months ago

This fix is available in 5.4.2 now: https://github.com/mobxjs/mobx-state-tree/releases/tag/v5.4.2, will be shipped with v6 as well.