Skip to content

Commit 043eb35

Browse files
committed
feat(effectScope): allow multiple calls by tracking call count
1 parent ef6986f commit 043eb35

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

packages/reactivity/__tests__/effectScope.spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,19 @@ describe('reactivity/effect/scope', () => {
296296
})
297297
})
298298

299+
it('calling on() and off() multiple times inside an active scope should not break currentScope', () => {
300+
const parentScope = effectScope()
301+
parentScope.run(() => {
302+
const childScope = effectScope(true)
303+
childScope.on()
304+
childScope.on()
305+
childScope.off()
306+
childScope.off()
307+
childScope.off()
308+
expect(getCurrentScope()).toBe(parentScope)
309+
})
310+
})
311+
299312
it('should pause/resume EffectScope', async () => {
300313
const counter = reactive({ num: 0 })
301314
const fnSpy = vi.fn(() => counter.num)

packages/reactivity/src/effectScope.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ export class EffectScope {
88
* @internal
99
*/
1010
private _active = true
11+
/**
12+
* @internal track `on` calls, allow `on` call multiple times
13+
*/
14+
private _onCallCount = 0
1115
/**
1216
* @internal
1317
*/
@@ -105,16 +109,22 @@ export class EffectScope {
105109
* @internal
106110
*/
107111
on(): void {
108-
this.prevScope = activeEffectScope
109-
activeEffectScope = this
112+
this._onCallCount++
113+
if (this._onCallCount === 1) {
114+
this.prevScope = activeEffectScope
115+
activeEffectScope = this
116+
}
110117
}
111118

112119
/**
113120
* This should only be called on non-detached scopes
114121
* @internal
115122
*/
116123
off(): void {
117-
activeEffectScope = this.prevScope
124+
this._onCallCount = Math.max(0, this._onCallCount - 1)
125+
if (this._onCallCount === 0) {
126+
activeEffectScope = this.prevScope
127+
}
118128
}
119129

120130
stop(fromParent?: boolean): void {

0 commit comments

Comments
 (0)