From e9ea565d915cdffbad17bb78aa30af752dd4e5e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=B0smail=20Ar=C4=B1l=C4=B1k?= Date: Thu, 8 Mar 2018 18:31:40 +0300 Subject: [PATCH] polish: raise warning when Vue.set/delete is called on invalid values (#7452) close #7381 --- src/core/observer/index.js | 12 ++++++++++++ test/unit/modules/observer/observer.spec.js | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/core/observer/index.js b/src/core/observer/index.js index 244876b2..2ce0aabd 100644 --- a/src/core/observer/index.js +++ b/src/core/observer/index.js @@ -194,6 +194,12 @@ export function defineReactive ( * already exist. */ export function set (target: Array | 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) @@ -224,6 +230,12 @@ export function set (target: Array | Object, key: any, val: any): any { * Delete a property and trigger change if necessary. */ export function del (target: Array | 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 diff --git a/test/unit/modules/observer/observer.spec.js b/test/unit/modules/observer/observer.spec.js index 3ed7a3a4..20026823 100644 --- a/test/unit/modules/observer/observer.spec.js +++ b/test/unit/modules/observer/observer.spec.js @@ -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