Skip to content

Commit 0a301d4

Browse files
authoredApr 12, 2022
fix(reactivity): fix currentScope loss when running detached effect scope (#5575)
1 parent cee1eaf commit 0a301d4

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed
 

‎packages/reactivity/__tests__/effectScope.spec.ts

+15-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ import {
66
onScopeDispose,
77
computed,
88
ref,
9-
ComputedRef
9+
ComputedRef,
10+
getCurrentScope
1011
} from '../src'
1112

1213
describe('reactivity/effect/scope', () => {
@@ -263,4 +264,17 @@ describe('reactivity/effect/scope', () => {
263264
expect(watchSpy).toHaveBeenCalledTimes(1)
264265
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
265266
})
267+
268+
it('getCurrentScope() stays valid when running a detached nested EffectScope', () => {
269+
const parentScope = new EffectScope()
270+
271+
parentScope.run(() => {
272+
const currentScope = getCurrentScope()
273+
expect(currentScope).toBeDefined()
274+
const detachedScope = new EffectScope(true)
275+
detachedScope.run(() => {})
276+
277+
expect(getCurrentScope()).toBe(currentScope)
278+
})
279+
})
266280
})

‎packages/reactivity/src/effectScope.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,13 @@ export class EffectScope {
88
effects: ReactiveEffect[] = []
99
cleanups: (() => void)[] = []
1010

11+
/**
12+
* only assinged by undetached scope
13+
*/
1114
parent: EffectScope | undefined
15+
/**
16+
* record undetached scopes
17+
*/
1218
scopes: EffectScope[] | undefined
1319
/**
1420
* track a child scope's index in its parent's scopes array for optimized
@@ -28,11 +34,12 @@ export class EffectScope {
2834

2935
run<T>(fn: () => T): T | undefined {
3036
if (this.active) {
37+
const currentEffectScope = activeEffectScope
3138
try {
3239
activeEffectScope = this
3340
return fn()
3441
} finally {
35-
activeEffectScope = this.parent
42+
activeEffectScope = currentEffectScope
3643
}
3744
} else if (__DEV__) {
3845
warn(`cannot run an inactive effect scope.`)

0 commit comments

Comments
 (0)
Please sign in to comment.