Skip to content

Commit

Permalink
fix(reactivity): lose activeEffectScope when effectScope(true)
Browse files Browse the repository at this point in the history
  • Loading branch information
a65162 committed Mar 19, 2022
1 parent 1070f12 commit 002402e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
16 changes: 15 additions & 1 deletion packages/reactivity/__tests__/effectScope.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
onScopeDispose,
computed,
ref,
ComputedRef
ComputedRef,
getCurrentScope,
} from '../src'

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

it('getCurrentScope() should not get undefined when new EffectScope(true) inside parentScope.run function ', () => {
const spy = jest.fn()
const parentScope = new EffectScope()

parentScope.run(() => {
const childScope = new EffectScope(true)
childScope.run(spy)

expect(getCurrentScope()).not.toBeUndefined()
expect(getCurrentScope() === parentScope).toBe(true)
})
})
})
18 changes: 16 additions & 2 deletions packages/reactivity/src/effectScope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,23 @@ export class EffectScope {
effects: ReactiveEffect[] = []
cleanups: (() => void)[] = []

/**
* only assinged by undetached scope
*/
parent: EffectScope | undefined
/**
* record undetached scopes
*/
scopes: EffectScope[] | undefined
/**
* track a child scope's index in its parent's scopes array for optimized
* removal
*/
private index: number | undefined
/**
* activeEffectScope in context not died should be recorded
*/
private aliveEffectScope: EffectScope | undefined

constructor(detached = false) {
if (!detached && activeEffectScope) {
Expand All @@ -29,22 +39,26 @@ export class EffectScope {
run<T>(fn: () => T): T | undefined {
if (this.active) {
try {
this.aliveEffectScope = activeEffectScope
activeEffectScope = this
return fn()
} finally {
activeEffectScope = this.parent
activeEffectScope = this.aliveEffectScope
delete this.aliveEffectScope
}
} else if (__DEV__) {
warn(`cannot run an inactive effect scope.`)
}
}

on() {
this.aliveEffectScope = activeEffectScope
activeEffectScope = this
}

off() {
activeEffectScope = this.parent
activeEffectScope = this.aliveEffectScope
delete this.aliveEffectScope
}

stop(fromParent?: boolean) {
Expand Down

0 comments on commit 002402e

Please sign in to comment.