From c69c4bb59c114f2b5e03733b55ef9ace3087b5c3 Mon Sep 17 00:00:00 2001 From: Tycho Date: Tue, 20 May 2025 08:44:13 +0800 Subject: [PATCH] fix(watch): update `oldValue` before running `cb` to prevent stale value (#12296) close #12294 --- packages/reactivity/__tests__/watch.spec.ts | 12 ++++++++++++ packages/reactivity/src/watch.ts | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/reactivity/__tests__/watch.spec.ts b/packages/reactivity/__tests__/watch.spec.ts index 245acfd63b..9bec54e5f6 100644 --- a/packages/reactivity/__tests__/watch.spec.ts +++ b/packages/reactivity/__tests__/watch.spec.ts @@ -277,4 +277,16 @@ describe('watch', () => { expect(dummy).toEqual([1, 2, 3]) }) + + test('watch with immediate reset and sync flush', () => { + const value = ref(false) + + watch(value, () => { + value.value = false + }) + + value.value = true + value.value = true + expect(value.value).toBe(false) + }) }) diff --git a/packages/reactivity/src/watch.ts b/packages/reactivity/src/watch.ts index 659121ca34..648e6481b1 100644 --- a/packages/reactivity/src/watch.ts +++ b/packages/reactivity/src/watch.ts @@ -264,11 +264,11 @@ export function watch( : oldValue, boundCleanup, ] + oldValue = newValue call ? call(cb!, WatchErrorCodes.WATCH_CALLBACK, args) : // @ts-expect-error cb!(...args) - oldValue = newValue } finally { activeWatcher = currentWatcher } -- 2.47.2