Skip to content

Commit 002402e

Browse files
committed
fix(reactivity): lose activeEffectScope when effectScope(true)
1 parent 1070f12 commit 002402e

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

packages/reactivity/__tests__/effectScope.spec.ts

Lines changed: 15 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', () => {
@@ -263,4 +264,17 @@ describe('reactivity/effect/scope', () => {
263264
expect(watchSpy).toHaveBeenCalledTimes(1)
264265
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
265266
})
267+
268+
it('getCurrentScope() should not get undefined when new EffectScope(true) inside parentScope.run function ', () => {
269+
const spy = jest.fn()
270+
const parentScope = new EffectScope()
271+
272+
parentScope.run(() => {
273+
const childScope = new EffectScope(true)
274+
childScope.run(spy)
275+
276+
expect(getCurrentScope()).not.toBeUndefined()
277+
expect(getCurrentScope() === parentScope).toBe(true)
278+
})
279+
})
266280
})

packages/reactivity/src/effectScope.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,23 @@ 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
1521
* removal
1622
*/
1723
private index: number | undefined
24+
/**
25+
* activeEffectScope in context not died should be recorded
26+
*/
27+
private aliveEffectScope: EffectScope | undefined
1828

1929
constructor(detached = false) {
2030
if (!detached && activeEffectScope) {
@@ -29,22 +39,26 @@ export class EffectScope {
2939
run<T>(fn: () => T): T | undefined {
3040
if (this.active) {
3141
try {
42+
this.aliveEffectScope = activeEffectScope
3243
activeEffectScope = this
3344
return fn()
3445
} finally {
35-
activeEffectScope = this.parent
46+
activeEffectScope = this.aliveEffectScope
47+
delete this.aliveEffectScope
3648
}
3749
} else if (__DEV__) {
3850
warn(`cannot run an inactive effect scope.`)
3951
}
4052
}
4153

4254
on() {
55+
this.aliveEffectScope = activeEffectScope
4356
activeEffectScope = this
4457
}
4558

4659
off() {
47-
activeEffectScope = this.parent
60+
activeEffectScope = this.aliveEffectScope
61+
delete this.aliveEffectScope
4862
}
4963

5064
stop(fromParent?: boolean) {

0 commit comments

Comments
 (0)