Skip to content

fix(reactivity): ensure computed re-evaluates after dep cleanup #12021

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

Closed
wants to merge 4 commits into from
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/reactivity/__tests__/computed.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1037,4 +1037,22 @@ describe('reactivity/computed', () => {
state.a++
expect(pp.value).toBe(2)
})

test('computed value updates correctly after dep cleanup', () => {
const obj = reactive({ foo: 1, flag: 1 })
const c1 = computed(() => obj.foo)

let foo
effect(() => {
foo = obj.flag ? (obj.foo, c1.value) : 0
})
expect(foo).toBe(1)

obj.flag = 0
expect(foo).toBe(0)

obj.foo = 2
obj.flag = 1
expect(foo).toBe(2)
})
})
12 changes: 10 additions & 2 deletions packages/reactivity/src/effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ function cleanupDeps(sub: Subscriber, fromComputed = false) {
sub.depsTail = tail
}

function isDirty(sub: Subscriber): boolean {
function isDirty(sub: Subscriber, isComputed = false): boolean {
for (let link = sub.deps; link; link = link.nextDep) {
if (
link.dep.version !== link.version ||
Expand All @@ -331,6 +331,14 @@ function isDirty(sub: Subscriber): boolean {
) {
return true
}

if (
isComputed &&
link.dep.map &&
link.dep.map.get(link.dep.key) !== link.dep
) {
return true
}
}
// @ts-expect-error only for backwards compatibility where libs manually set
// this flag - e.g. Pinia's testing module
Expand Down Expand Up @@ -370,7 +378,7 @@ export function refreshComputed(computed: ComputedRefImpl): undefined {
dep.version > 0 &&
!computed.isSSR &&
computed.deps &&
!isDirty(computed)
!isDirty(computed, true)
) {
computed.flags &= ~EffectFlags.RUNNING
return
Expand Down