Skip to content

fix(lifecycle): scope might changed when call hook #13070

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

Merged
merged 2 commits into from
Oct 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/core/instance/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
invokeWithErrorHandling
} from '../util/index'
import { currentInstance, setCurrentInstance } from 'v3/currentInstance'
import { getCurrentScope } from 'v3/reactivity/effectScope'
import { syncSetupProxy } from 'v3/apiSetup'

export let activeInstance: any = null
Expand Down Expand Up @@ -398,7 +399,8 @@ export function callHook(
) {
// #7573 disable dep collection when invoking lifecycle hooks
pushTarget()
const prev = currentInstance
const prevInst = currentInstance
const prevScope = getCurrentScope()
setContext && setCurrentInstance(vm)
const handlers = vm.$options[hook]
const info = `${hook} hook`
Expand All @@ -410,6 +412,10 @@ export function callHook(
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook)
}
setContext && setCurrentInstance(prev)
if (setContext) {
setCurrentInstance(prevInst)
prevScope && prevScope.on()
}

popTarget()
}
25 changes: 25 additions & 0 deletions test/unit/features/v3/reactivity/effectScope.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Vue from 'vue'
import { nextTick } from 'core/util'
import {
watch,
Expand Down Expand Up @@ -290,4 +291,28 @@ describe('reactivity/effectScope', () => {
expect(getCurrentScope()).toBe(parentScope)
})
})

it('scope should not break currentScope when component call hooks', () => {
const scope = new EffectScope()
const vm = new Vue({
template: `
<div>
<div v-if="show" />
</div>
`,
data() {
return {
show: false
}
}
}).$mount()

scope.run(() => {
// call renderTriggered hook here
vm.show = true
// this effect should be collected by scope not the component scope
effect(() => {})
})
expect(scope.effects.length).toBe(1)
})
})