Skip to content

Commit

Permalink
fix(effectScope): should stop along with parent component
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jul 16, 2021
1 parent 0cada69 commit 784d96c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/apis/effectScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ export function recordEffectScope(
scope = scope || activeEffectScope
if (scope && scope.active) {
scope.effects.push(effect)
return
}
// destory on parent component unmounted
const vm = getCurrentInstance()?.proxy
vm && vm.$on('hook:destroyed', () => effect.stop())
}

export function effectScope(detached?: boolean) {
Expand Down
31 changes: 31 additions & 0 deletions test/v3/reactivity/effectScope.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
computed,
ref,
ComputedRef,
createApp,
} from '../../../src'
import { mockWarn } from '../../helpers'

Expand Down Expand Up @@ -251,4 +252,34 @@ describe('reactivity/effect/scope', () => {
expect(watchSpy).toHaveBeenCalledTimes(1)
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
})

it('should stop along with parent component', async () => {
let dummy, doubled
const counter = reactive({ num: 0 })

const root = document.createElement('div')
const vm = createApp({
setup() {
const scope = new EffectScope()
scope.run(() => {
watchEffect(() => (dummy = counter.num))
watchEffect(() => (doubled = counter.num * 2))
})
},
})
vm.mount(root)

expect(dummy).toBe(0)
counter.num = 7
await nextTick()
expect(dummy).toBe(7)
expect(doubled).toBe(14)

vm.unmount()

counter.num = 6
await nextTick()
expect(dummy).toBe(7)
expect(doubled).toBe(14)
})
})

0 comments on commit 784d96c

Please sign in to comment.