From 8d6f2607efbd49edda0c2ee54d3d3ec45861b956 Mon Sep 17 00:00:00 2001 From: Michel Weststrate Date: Thu, 31 Aug 2023 10:04:59 +0200 Subject: [PATCH] fix #3747 --- .../mobx/__tests__/v5/base/observables.js | 10 ++++++++++ packages/mobx/src/core/atom.ts | 20 +++++++++---------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/packages/mobx/__tests__/v5/base/observables.js b/packages/mobx/__tests__/v5/base/observables.js index 86c5d7e0f..486cd7751 100644 --- a/packages/mobx/__tests__/v5/base/observables.js +++ b/packages/mobx/__tests__/v5/base/observables.js @@ -2505,3 +2505,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 + }) +}) diff --git a/packages/mobx/src/core/atom.ts b/packages/mobx/src/core/atom.ts index c9e5315ad..57332cce0 100644 --- a/packages/mobx/src/core/atom.ts +++ b/packages/mobx/src/core/atom.ts @@ -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() }