Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(reactivity): watchEffect should deduplicate multiple onCleanup calls for the same function #12394

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions packages/reactivity/src/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ const INITIAL_WATCHER_VALUE = {}

export type WatchScheduler = (job: () => void, isFirstRun: boolean) => void

const cleanupMap: WeakMap<ReactiveEffect, (() => void)[]> = new WeakMap()
const cleanupMap: WeakMap<ReactiveEffect, Set<() => void>> = new WeakMap()
let activeWatcher: ReactiveEffect | undefined = undefined

/**
Expand Down Expand Up @@ -107,8 +107,8 @@ export function onWatcherCleanup(
): void {
if (owner) {
let cleanups = cleanupMap.get(owner)
if (!cleanups) cleanupMap.set(owner, (cleanups = []))
cleanups.push(cleanupFn)
if (!cleanups) cleanupMap.set(owner, (cleanups = new Set()))
cleanups.add(cleanupFn)
} else if (__DEV__ && !failSilently) {
warn(
`onWatcherCleanup() was called when there was no active watcher` +
Expand Down Expand Up @@ -295,9 +295,9 @@ export function watch(
const cleanups = cleanupMap.get(effect)
if (cleanups) {
if (call) {
call(cleanups, WatchErrorCodes.WATCH_CLEANUP)
call([...cleanups], WatchErrorCodes.WATCH_CLEANUP)
} else {
for (const cleanup of cleanups) cleanup()
cleanups.forEach(cleanup => cleanup())
}
cleanupMap.delete(effect)
}
Expand Down
14 changes: 14 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1564,6 +1564,20 @@ describe('api: watch', () => {
expect(cb).toHaveBeenCalledTimes(1)
})

// #3341
test('watchEffect should allow multiple onCleanup calls', async () => {
shengxj1 marked this conversation as resolved.
Show resolved Hide resolved
const spy1 = vi.fn()
const spy2 = vi.fn()
const stop = watchEffect(onCleanup => {
onCleanup(spy1)
onCleanup(spy1)
onCleanup(spy2)
})
stop()
expect(spy1).toHaveBeenCalledTimes(1)
expect(spy2).toHaveBeenCalledTimes(1)
})

// #5151
test('OnCleanup also needs to be cleaned,', async () => {
const spy1 = vi.fn()
Expand Down