Skip to content

fix(reactivity): avoid error during nested watch stop #5806

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

Closed
wants to merge 11 commits into from
8 changes: 6 additions & 2 deletions packages/reactivity/src/effectScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,12 @@ export class EffectScope {
stop(fromParent?: boolean) {
if (this._active) {
let i, l
for (i = 0, l = this.effects.length; i < l; i++) {
this.effects[i].stop()
// #5783
// effects will be changed when a watcher stoped.
// so we need to copy it for iteration.
const effectsToStop = this.effects.slice()
for (i = 0, l = effectsToStop.length; i < l; i++) {
effectsToStop[i].stop()
}
for (i = 0, l = this.cleanups.length; i < l; i++) {
this.cleanups[i]()
Expand Down
27 changes: 27 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1290,6 +1290,33 @@ describe('api: watch', () => {
expect(spy).toHaveBeenCalledTimes(2)
})

test('handle nested watcher stop properly', () => {
let instance: ComponentInternalInstance
const Comp = {
setup() {
instance = getCurrentInstance()!
watch(
() => 1,
(val, oldVal, onCleanup) => {
const stop = watch(
() => 2,
() => {},
)
onCleanup(stop)
},
{ immediate: true },
)
return () => ''
},
}
const root = nodeOps.createElement('div')
createApp(Comp).mount(root)
expect(instance!.scope.effects.length).toBe(3)

instance!.scope.stop()
expect(instance!.scope.effects[0].active).toBe(false)
})

it('watching sources: ref<any[]>', async () => {
const foo = ref([1])
const spy = vi.fn()
Expand Down