Skip to content

Commit

Permalink
fix(reactivity): ensure watcher with once: true are properly removed …
Browse files Browse the repository at this point in the history
…from effect scope (#11665)
  • Loading branch information
yangxiuxiu1115 authored Aug 20, 2024
1 parent f2ea25d commit fbc0c42
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
20 changes: 10 additions & 10 deletions packages/reactivity/src/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,18 +206,26 @@ export function watch(
getter = () => traverse(baseGetter(), depth)
}

const scope = getCurrentScope()
const watchHandle: WatchHandle = () => {
effect.stop()
if (scope) {
remove(scope.effects, effect)
}
}

if (once) {
if (cb) {
const _cb = cb
cb = (...args) => {
_cb(...args)
effect.stop()
watchHandle()
}
} else {
const _getter = getter
getter = () => {
_getter()
effect.stop()
watchHandle()
}
}
}
Expand Down Expand Up @@ -317,14 +325,6 @@ export function watch(
effect.run()
}

const scope = getCurrentScope()
const watchHandle: WatchHandle = () => {
effect.stop()
if (scope) {
remove(scope.effects, effect)
}
}

watchHandle.pause = effect.pause.bind(effect)
watchHandle.resume = effect.resume.bind(effect)
watchHandle.stop = watchHandle
Expand Down
5 changes: 5 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1771,6 +1771,11 @@ describe('api: watch', () => {
expect(scope.effects.length).toBe(1)
unwatch!()
expect(scope.effects.length).toBe(0)

scope.run(() => {
watch(num, () => {}, { once: true, immediate: true })
})
expect(scope.effects.length).toBe(0)
})

// simplified case of VueUse syncRef
Expand Down

0 comments on commit fbc0c42

Please sign in to comment.