Unintuitive Proxy behavior violating set item uniqueness constraint
Vue version
@9f8e98a
Link to minimal reproduction
Steps to reproduce
Simply open the console, you should see an error.
What is expected?
Sets are expected by the user of the language to behave a certain way, different from arrays. Specifically, they differ in this core aspect:
Pushing an item into an array changes the array, regardless of if the item was already in the array. Adding an item to a set changes the set if and only if the item was not already in the set.
What is actually happening?
Vue violates this behavior. It seems to get tripped up as the Set is being initilaized with an object already inside it. When .add
is called, it first unproxies the object before adding it to the Set. I do not understand this behavior and I think it's counterintuitive. The thing that trips me up in this case is that .has
still returns true here. So, .has
returns true, yet .add
changes the set. Makes no sense.
Either .has
should return false here, or, the better solution, .add
should not change the set.
System Info
System:
OS: macOS 13.3.1
CPU: (10) arm64 Apple M1 Pro
Memory: 118.56 MB / 16.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 18.14.2 - /opt/homebrew/opt/node@18/bin/node
Yarn: 1.22.19 - /opt/homebrew/bin/yarn
npm: 9.5.0 - /opt/homebrew/opt/node@18/bin/npm
Browsers:
Chrome: 114.0.5735.133
Safari: 16.4
Any additional comments?
Ran into this bug while replacing a bunch of "if not includes, push item" logic by switching to Set.
Workarounds for I've found for this are:
- Initializing with the unproxied elements:
const set = reactive(new Set(items.map(toRaw)))
- Manually initializing the Set using a loop:
const set = reactive(new Set()) for (const item of items) set.add(item)