Skip to content

Commit 73fd810

Browse files
authoredNov 10, 2023
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

+35
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

+2-1
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)
Please sign in to comment.