Skip to content
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

refactor(effectScope): restore parent scope after detached scope run / off #5669

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 28 additions & 1 deletion packages/reactivity/__tests__/effectScope.spec.ts
Expand Up @@ -6,7 +6,8 @@ import {
onScopeDispose,
computed,
ref,
ComputedRef
ComputedRef,
getCurrentScope
} from '../src'

describe('reactivity/effect/scope', () => {
Expand Down Expand Up @@ -264,3 +265,29 @@ describe('reactivity/effect/scope', () => {
expect(watchEffectSpy).toHaveBeenCalledTimes(2)
})
})

it('getCurrentScope() stays valid when running a detached nested EffectScope', () => {
const parentScope = new EffectScope()

parentScope.run(() => {
const currentScope = getCurrentScope()
expect(currentScope).toBeDefined()
const detachedScope = new EffectScope(true)
detachedScope.run(() => {})

expect(getCurrentScope()).toBe(currentScope)
})
})

it('getCurrentScope() stays valid when offed a detached nested EffectScope', () => {
const parentScope = new EffectScope()

parentScope.run(() => {
const currentScope = getCurrentScope()
expect(currentScope).toBeDefined()
const detachedScope = new EffectScope(true)
detachedScope.off()

expect(getCurrentScope()).toBe(currentScope)
})
})
8 changes: 4 additions & 4 deletions packages/reactivity/src/effectScope.ts
Expand Up @@ -17,8 +17,8 @@ export class EffectScope {
private index: number | undefined

constructor(detached = false) {
this.parent = activeEffectScope
if (!detached && activeEffectScope) {
this.parent = activeEffectScope
this.index =
(activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(
this
Expand Down Expand Up @@ -62,12 +62,12 @@ export class EffectScope {
}
}
// nested scope, dereference from parent to avoid memory leaks
if (this.parent && !fromParent) {
if (this.index !== undefined && this.parent && !fromParent) {
// optimized O(1) removal
const last = this.parent.scopes!.pop()
if (last && last !== this) {
this.parent.scopes![this.index!] = last
last.index = this.index!
this.parent.scopes![this.index] = last
last.index = this.index
}
}
this.active = false
Expand Down