core icon indicating copy to clipboard operation
core copied to clipboard

Deep watchers miss nested changes to objects used as Map keys

Open zhengdaodeguL opened this issue 1 week ago • 1 comments

Deep watchers miss nested changes to objects used as Map keys

Describe the bug

When a reactive Map is watched deeply, nested mutations on an object used only as a key do not trigger the watcher. Deep traversal visits Map values but does not traverse their keys.

Minimal reproduction

Add this test to packages/reactivity/__tests__/watch.spec.ts:

import { reactive, watch } from '../src'

test('should traverse Map keys in deep watchers', () => {
  const key = reactive({ nested: { value: 0 } })
  const map = reactive(new Map([[key, 'value']]))
  const callback = vi.fn()

  watch(map, callback)

  key.nested.value++
  expect(callback).toHaveBeenCalledTimes(1)
})

Run it with:

pnpm vitest run packages/reactivity/__tests__/watch.spec.ts -t 'should traverse Map keys in deep watchers'

Expected behavior

The callback runs once after the nested key property changes.

Actual behavior

The callback is not called.

Environment

  • Node.js v24.22.1
  • Linux

zhengdaodeguL avatar Nov 22 '26 11:11 zhengdaodeguL

I'd like to take this one if nobody is on it yet.

The cause seems to be in traverse() (packages/reactivity/src/watch.ts): Sets and Maps share one branch, value.forEach((v) => traverse(v, depth, seen)), so for a Map only the values are visited, never the keys. Since the reactive Map's forEach already passes the wrapped key as the second argument, the fix could be to split the branch and, for Maps, traverse both v and k (Sets stay as they are, since their forEach passes the value twice).

I'd add the test from the issue to packages/reactivity/__tests__/watch.spec.ts, plus one for a deep: 1 watcher to make sure the depth limit still applies to keys the same way it does to values. Does that sound right?

moonlorddev avatar Nov 22 '26 15:11 moonlorddev