Skip to content
Myr

fix: make sure getters are invoked with the correct scope, fixes #558

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by Michel Weststrate · parent e300fa4 · Browse files · 2 files+18 added−11 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+18 added−11 removed

  • tests:+2 added−2 removed
  • other:+16 added−9 removed

2 files+18 added−11 removed

modified:__tests__/base.js+2 added-2 removed
2099 unmodified lines
2100 return this._bar2101 }2102 syncFoo() {2103 this.foo = this.bar.baz2104 this.bar.baz++2105 }2106 }2107 const state = new State()21082109 it("should use a method to assing a field using a getter that return a non primitive object", () => {2110 const newState = produce(state, draft => {2111 draft.syncFoo()2111 expect(draft.bar).toEqual({baz: 1})2112 })2113 expect(newState.foo).toEqual(1)2114 expect(newState.bar).toEqual({baz: 1})2114 expect(newState.bar).toEqual({baz: 2})2115 expect(state.bar).toEqual({baz: 1})2116 })2117 })2118
94 unmodified lines
modified:src/core/proxy.ts+16 added-9 removed
17 unmodified lines
18 createProxy,19 ProxyTypeProxyObject,20 ProxyTypeProxyArray21} from "../internal"22import {isPlainObject} from "../utils/common"2324interface ProxyBaseState extends ImmerBaseState {25 assigned_: {26 [property: string]: boolean
87 unmodified lines
114 if (!state.modified_ && has(drafts, prop)) {115 return drafts![prop as any]116 }117117 const value = latest(state)[prop]118 const l = latest(state)119 const desc = Object.getOwnPropertyDescriptor(120 isPlainObject(l) ? l : Object.getPrototypeOf(l),121 prop122 )123 // If the prop is a getter, don't proxy the full prop, but invoke the getter with the correct scope. Fixes #558124 if (desc?.get) return desc.get.call(state.draft_)125126 const value = l[prop]127 if (state.finalized_ || !isDraftable(value)) {128 return value129 }130
5 unmodified lines
136 // @ts-ignore137 drafts = state.copy_138 }139140 // const desc = Object.getOwnPropertyDescriptor(latest(state), prop)141 // Don't create and store proxies for getters (they might return drafts though)142 // See #558143 // if (!desc || desc.get) return value144 return (drafts![prop as any] = createProxy(145 state.scope_.immer_,146 value,147 state
103 unmodified lines
251 state.type_ === ProxyTypeProxyArray252 ) {253 const copy = (state.copy_ = shallowCopy(state.base_))254 each(state.drafts_!, (key, value) => {242 const descProto = Object.getOwnPropertyDescriptor(243 Object.getPrototypeOf(copy),244 key245 )246 if (!(descProto && descProto.get && !descProto.set)) {247 // @ts-ignore248 copy[key] = value255 // @ts-ignore256 copy[key] = value249 }257 })258 state.drafts_ = undefined259 }260
11 unmodified lines