Skip to content

Commit a901c60

Browse files
committed
refactor(effectScope): restore parent scope after detached scope run / off
1 parent 245230e commit a901c60

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed

packages/reactivity/__tests__/effectScope.spec.ts

Lines changed: 28 additions & 1 deletion
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', () => {
@@ -264,3 +265,29 @@ describe('reactivity/effect/scope', () => {
264265
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
265266
})
266267
})
268+
269+
it('getCurrentScope() stays valid when running a detached nested EffectScope', () => {
270+
const parentScope = new EffectScope()
271+
272+
parentScope.run(() => {
273+
const currentScope = getCurrentScope()
274+
expect(currentScope).toBeDefined()
275+
const detachedScope = new EffectScope(true)
276+
detachedScope.run(() => {})
277+
278+
expect(getCurrentScope()).toBe(currentScope)
279+
})
280+
})
281+
282+
it('getCurrentScope() stays valid when offed a detached nested EffectScope', () => {
283+
const parentScope = new EffectScope()
284+
285+
parentScope.run(() => {
286+
const currentScope = getCurrentScope()
287+
expect(currentScope).toBeDefined()
288+
const detachedScope = new EffectScope(true)
289+
detachedScope.off()
290+
291+
expect(getCurrentScope()).toBe(currentScope)
292+
})
293+
})

packages/reactivity/src/effectScope.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ export class EffectScope {
1717
private index: number | undefined
1818

1919
constructor(detached = false) {
20+
this.parent = activeEffectScope
2021
if (!detached && activeEffectScope) {
21-
this.parent = activeEffectScope
2222
this.index =
2323
(activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(
2424
this
@@ -62,12 +62,12 @@ export class EffectScope {
6262
}
6363
}
6464
// nested scope, dereference from parent to avoid memory leaks
65-
if (this.parent && !fromParent) {
65+
if (this.index !== undefined && this.parent && !fromParent) {
6666
// optimized O(1) removal
6767
const last = this.parent.scopes!.pop()
6868
if (last && last !== this) {
69-
this.parent.scopes![this.index!] = last
70-
last.index = this.index!
69+
this.parent.scopes![this.index] = last
70+
last.index = this.index
7171
}
7272
}
7373
this.active = false

0 commit comments

Comments
 (0)