Skip to content

Commit

Permalink
fix(reactivity): prevent overwriting next property during batch pro…
Browse files Browse the repository at this point in the history
…cessing
  • Loading branch information
jh-leong committed Sep 29, 2024
1 parent 29de6f8 commit 60f7a7b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/reactivity/__tests__/watch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,4 +260,21 @@ describe('watch', () => {
src.value = 10
expect(spy).toHaveBeenCalledTimes(2)
})

test('should ensure correct execution order in batch processing', () => {
const dummy: number[] = []
const n1 = ref(0)
const n2 = ref(0)
const sum = computed(() => n1.value + n2.value)
watch(n1, () => {
dummy.push(1)
n2.value++
})
watch(sum, () => dummy.push(2))
watch(n1, () => dummy.push(3))

n1.value++

expect(dummy).toEqual([1, 2, 3])
})
})
3 changes: 3 additions & 0 deletions packages/reactivity/src/effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,9 @@ let batchedSub: Subscriber | undefined

export function batch(sub: Subscriber): void {
sub.flags |= EffectFlags.NOTIFIED
// If sub.next is set, the subscriber is already in a batch,
// return to avoid overwriting it and losing previous subscriptions.
if (sub.next) return
sub.next = batchedSub
batchedSub = sub
}
Expand Down

0 comments on commit 60f7a7b

Please sign in to comment.