From d9162dfc2ee0c3a369fb9bf32ff413e74761bee6 Mon Sep 17 00:00:00 2001 From: Evan You Date: Mon, 8 Jan 2024 18:20:29 +0800 Subject: [PATCH] fix(scheduler): sort nested postFlushCbs close #10003 --- .../runtime-core/__tests__/scheduler.spec.ts | 21 +++++++++++++++++++ packages/runtime-core/src/scheduler.ts | 6 +++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/runtime-core/__tests__/scheduler.spec.ts b/packages/runtime-core/__tests__/scheduler.spec.ts index c6fe292fb7b..781aa6eb0b7 100644 --- a/packages/runtime-core/__tests__/scheduler.spec.ts +++ b/packages/runtime-core/__tests__/scheduler.spec.ts @@ -610,4 +610,25 @@ describe('scheduler', () => { expect(await p).toBe(1) expect(fn).toHaveBeenCalledTimes(1) }) + + // #10003 + test('nested flushPostFlushCbs', async () => { + const calls: string[] = [] + const cb1 = () => calls.push('cb1') + // cb1 has no id + const cb2 = () => calls.push('cb2') + cb2.id = -1 + const queueAndFlush = (hook: Function) => { + queuePostFlushCb(hook) + flushPostFlushCbs() + } + + queueAndFlush(() => { + queuePostFlushCb([cb1, cb2]) + flushPostFlushCbs() + }) + + await nextTick() + expect(calls).toEqual(['cb2', 'cb1']) + }) }) diff --git a/packages/runtime-core/src/scheduler.ts b/packages/runtime-core/src/scheduler.ts index 78b4d7d9a98..b8d1445a183 100644 --- a/packages/runtime-core/src/scheduler.ts +++ b/packages/runtime-core/src/scheduler.ts @@ -164,7 +164,9 @@ export function flushPreFlushCbs( export function flushPostFlushCbs(seen?: CountMap) { if (pendingPostFlushCbs.length) { - const deduped = [...new Set(pendingPostFlushCbs)] + const deduped = [...new Set(pendingPostFlushCbs)].sort( + (a, b) => getId(a) - getId(b), + ) pendingPostFlushCbs.length = 0 // #1947 already has active queue, nested flushPostFlushCbs call @@ -178,8 +180,6 @@ export function flushPostFlushCbs(seen?: CountMap) { seen = seen || new Map() } - activePostFlushCbs.sort((a, b) => getId(a) - getId(b)) - for ( postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length;