Skip to content

Commit

Permalink
polish: raise warning when Vue.set/delete is called on invalid values (
Browse files Browse the repository at this point in the history
  • Loading branch information
ismailarilik authored and aJean committed Aug 19, 2020
1 parent 5ee973c commit 5898de1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/core/observer/index.js
Expand Up @@ -194,6 +194,12 @@ export function defineReactive (
* already exist.
*/
export function set (target: Array<any> | Object, key: any, val: any): any {
if (process.env.NODE_ENV !== 'production' &&
!Array.isArray(target) &&
!isObject(target)
) {
warn(`Cannot set reactive property on non-object/array value: ${target}`)
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
target.splice(key, 1, val)
Expand Down Expand Up @@ -224,6 +230,12 @@ export function set (target: Array<any> | Object, key: any, val: any): any {
* Delete a property and trigger change if necessary.
*/
export function del (target: Array<any> | Object, key: any) {
if (process.env.NODE_ENV !== 'production' &&
!Array.isArray(target) &&
!isObject(target)
) {
warn(`Cannot delete reactive property on non-object/array value: ${target}`)
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.splice(key, 1)
return
Expand Down
12 changes: 12 additions & 0 deletions test/unit/modules/observer/observer.spec.js
Expand Up @@ -356,6 +356,18 @@ describe('Observer', () => {
})
})

it('warn set/delete on non valid values', () => {
try {
setProp(null, 'foo', 1)
} catch (e) {}
expect(`Cannot set reactive property on non-object/array value`).toHaveBeenWarned()

try {
delProp(null, 'foo')
} catch (e) {}
expect(`Cannot delete reactive property on non-object/array value`).toHaveBeenWarned()
})

it('should lazy invoke existing getters', () => {
const obj = {}
let called = false
Expand Down

0 comments on commit 5898de1

Please sign in to comment.