Skip to content
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

fix(reactivity): correctly handle method calls on user-extended arrays #11760

Merged
merged 3 commits into from
Sep 3, 2024
Merged
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
21 changes: 21 additions & 0 deletions packages/reactivity/__tests__/reactiveArray.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,27 @@ describe('reactivity/reactive/Array', () => {
expect(state.things.forEach('foo', 'bar', 'baz')).toBeUndefined()
expect(state.things.map('foo', 'bar', 'baz')).toEqual(['1', '2', '3'])
expect(state.things.some('foo', 'bar', 'baz')).toBe(true)

{
class Collection extends Array {
find(matcher: any) {
return super.find(matcher)
}
}

const state = reactive({
// @ts-expect-error
things: new Collection({ foo: '' }),
})

const bar = computed(() => {
return state.things.find((obj: any) => obj.foo === 'bar')
})
bar.value
state.things[0].foo = 'bar'

expect(bar.value).toEqual({ foo: 'bar' })
}
})
})
})
10 changes: 7 additions & 3 deletions packages/reactivity/src/arrayInstrumentations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,9 +242,13 @@ function apply(
const needsWrap = arr !== self && !isShallow(self)
// @ts-expect-error our code is limited to es2016 but user code is not
const methodFn = arr[method]
// @ts-expect-error
if (methodFn !== arrayProto[method]) {
const result = methodFn.apply(arr, args)

// #11759
// If the method being called is from a user-extended Array, the arguments will be unknown
// (unknown order and unknown parameter types). In this case, we skip the shallowReadArray
// handling and directly call apply with self.
if (methodFn !== arrayProto[method as any]) {
const result = methodFn.apply(self, args)
return needsWrap ? toReactive(result) : result
}

Expand Down