Skip to content

Commit 84033f0

Browse files
committed
fix: make cleanup passed into watch callback bound
1 parent 4b92fca commit 84033f0

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

packages/reactivity/__tests__/watch.spec.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ describe('watch', () => {
115115
])
116116
})
117117

118-
test('watch with onEffectCleanup', async () => {
118+
test('watch with onWatcherCleanup', async () => {
119119
let dummy = 0
120120
let source: Ref<number>
121121
const scope = new EffectScope()
@@ -146,7 +146,7 @@ describe('watch', () => {
146146
expect(dummy).toBe(30)
147147
})
148148

149-
test('nested calls to baseWatch and onEffectCleanup', async () => {
149+
test('nested calls to baseWatch and onWatcherCleanup', async () => {
150150
let calls: string[] = []
151151
let source: Ref<number>
152152
let copyist: Ref<number>

packages/reactivity/src/watch.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -96,11 +96,11 @@ export function getCurrentWatcher(): ReactiveEffect<any> | undefined {
9696
export function onWatcherCleanup(
9797
cleanupFn: () => void,
9898
failSilently = false,
99+
owner: ReactiveEffect | undefined = activeWatcher,
99100
): void {
100-
if (activeWatcher) {
101-
const cleanups =
102-
cleanupMap.get(activeWatcher) ||
103-
cleanupMap.set(activeWatcher, []).get(activeWatcher)!
101+
if (owner) {
102+
let cleanups = cleanupMap.get(owner)
103+
if (!cleanups) cleanupMap.set(owner, (cleanups = []))
104104
cleanups.push(cleanupFn)
105105
} else if (__DEV__ && !failSilently) {
106106
warn(
@@ -137,6 +137,7 @@ export function watch(
137137
}
138138

139139
let effect: ReactiveEffect
140+
let boundCleanup: typeof onWatcherCleanup
140141
let getter: () => any
141142
let cleanup: (() => void) | undefined
142143
let forceTrigger = false
@@ -184,8 +185,8 @@ export function watch(
184185
activeWatcher = effect
185186
try {
186187
return call
187-
? call(source, WatchErrorCodes.WATCH_CALLBACK, [onWatcherCleanup])
188-
: source(onWatcherCleanup)
188+
? call(source, WatchErrorCodes.WATCH_CALLBACK, [boundCleanup])
189+
: source(boundCleanup)
189190
} finally {
190191
activeWatcher = currentEffect
191192
}
@@ -254,7 +255,7 @@ export function watch(
254255
: isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE
255256
? []
256257
: oldValue,
257-
onWatcherCleanup,
258+
boundCleanup,
258259
]
259260
call
260261
? call(cb!, WatchErrorCodes.WATCH_CALLBACK, args)
@@ -276,6 +277,7 @@ export function watch(
276277
}
277278

278279
effect = new ReactiveEffect(getter)
280+
boundCleanup = fn => onWatcherCleanup(fn, false, effect)
279281
if (scheduler) {
280282
effect.scheduler = () => scheduler(job, false)
281283
} else {

0 commit comments

Comments
 (0)