Skip to content

Commit

Permalink
Fix #3747: computed values can get stale if backing observable was cr…
Browse files Browse the repository at this point in the history
…eated and updated outside tracking context (#3748)
  • Loading branch information
mweststrate authored Aug 31, 2023
1 parent 4ffc001 commit c8d9374
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 11 deletions.
5 changes: 5 additions & 0 deletions .changeset/witty-falcons-explode.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"mobx": patch
---

Fixed: #3747, computed values becoming stale if the underlying observable was created and updated outside a reactive context
11 changes: 11 additions & 0 deletions packages/mobx/__tests__/v5/base/observables.js
Original file line number Diff line number Diff line change
Expand Up @@ -2382,6 +2382,7 @@ test("state version updates correctly", () => {
o.x++
})

// expect(o.x).toBe(4) is 1?
prevStateVersion = getGlobalState().stateVersion
o.x++
expect(o.x).toBe(5)
Expand Down Expand Up @@ -2505,3 +2506,13 @@ test("state version does not update on observable creation", () => {
check(() => mobx.observable([0], { proxy: true }))
check(() => mobx.computed(() => 0))
})

test("#3747", () => {
mobx.runInAction(() => {
const o = observable.box(0)
const c = computed(() => o.get())
expect(c.get()).toBe(0)
o.set(1)
expect(c.get()).toBe(1) // would fail
})
})
20 changes: 9 additions & 11 deletions packages/mobx/src/core/atom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,21 +68,19 @@ export class Atom implements IAtom {
* Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate.
*/
public reportChanged() {
if (globalState.inBatch && this.batchId_ === globalState.batchId) {
// Called from the same batch this atom was created in.
return
if (!globalState.inBatch || this.batchId_ !== globalState.batchId) {
// We could update state version only at the end of batch,
// but we would still have to switch some global flag here to signal a change.
globalState.stateVersion =
globalState.stateVersion < Number.MAX_SAFE_INTEGER
? globalState.stateVersion + 1
: Number.MIN_SAFE_INTEGER
// Avoids the possibility of hitting the same globalState.batchId when it cycled through all integers (necessary?)
this.batchId_ = NaN
}
// Avoids the possibility of hitting the same globalState.batchId when it cycled through all integers (necessary?)
this.batchId_ = NaN

startBatch()
propagateChanged(this)
// We could update state version only at the end of batch,
// but we would still have to switch some global flag here to signal a change.
globalState.stateVersion =
globalState.stateVersion < Number.MAX_SAFE_INTEGER
? globalState.stateVersion + 1
: Number.MIN_SAFE_INTEGER
endBatch()
}

Expand Down

0 comments on commit c8d9374

Please sign in to comment.