Skip to content

Commit 73fd810

Browse files
authored
fix(reactivity): onCleanup also needs to be cleaned (#8655)
close #5151 close #7695
1 parent 3227e50 commit 73fd810

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

packages/runtime-core/__tests__/apiWatch.spec.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1205,4 +1205,39 @@ describe('api: watch', () => {
12051205
expect(countWE).toBe(3)
12061206
expect(countW).toBe(2)
12071207
})
1208+
1209+
// #5151
1210+
test('OnCleanup also needs to be cleaned,', async () => {
1211+
const spy1 = vi.fn()
1212+
const spy2 = vi.fn()
1213+
const num = ref(0)
1214+
1215+
watch(num, (value, oldValue, onCleanup) => {
1216+
if (value > 1) {
1217+
return
1218+
}
1219+
spy1()
1220+
onCleanup(() => {
1221+
// OnCleanup also needs to be cleaned
1222+
spy2()
1223+
})
1224+
})
1225+
1226+
num.value++
1227+
await nextTick()
1228+
expect(spy1).toHaveBeenCalledTimes(1)
1229+
expect(spy2).toHaveBeenCalledTimes(0)
1230+
1231+
num.value++
1232+
await nextTick()
1233+
1234+
expect(spy1).toHaveBeenCalledTimes(1)
1235+
expect(spy2).toHaveBeenCalledTimes(1)
1236+
1237+
num.value++
1238+
await nextTick()
1239+
// would not be calld when value>1
1240+
expect(spy1).toHaveBeenCalledTimes(1)
1241+
expect(spy2).toHaveBeenCalledTimes(1)
1242+
})
12081243
})

packages/runtime-core/src/apiWatch.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,10 +273,11 @@ function doWatch(
273273
getter = () => traverse(baseGetter())
274274
}
275275

276-
let cleanup: () => void
276+
let cleanup: (() => void) | undefined
277277
let onCleanup: OnCleanup = (fn: () => void) => {
278278
cleanup = effect.onStop = () => {
279279
callWithErrorHandling(fn, instance, ErrorCodes.WATCH_CLEANUP)
280+
cleanup = effect.onStop = undefined
280281
}
281282
}
282283

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy