uniapp [Vue warn]: Error in onLoad hook: “TypeError: Attempting to change the setter of an unconfigu

1. Background

I found this error when developing wechat applet with uniapp, and recorded how I solved it!

2. Error message

uniapp [Vue warn]: Error in onLoad hook: “TypeError: Attempting to change the setter of an unconfigurable property.”

3. Error reason:

Because in the Object.defineproperty method, the control property cannot be deleted. It is in an unconfigurable state.

4. Error analysis

Let’s take a look at the specific use of the Object.defineproperty method:

The role of Object.defineproperty is to define a new property directly on an object, or modify an existing property

Object.defineproperty parameter

The Object.defineproperty method needs to pass 3 parameters

Object.defineproperty(obj, prop, desc)

Parameter 1: obj The current object whose properties need to be defined

Parameter 2: prop The name of the property that currently needs to be defined

Parameter 3: The desc descriptor is generally an object

Generally, by assigning a value to the property of the object, the property of the object can be modified or deleted, but the property of the object can be defined by Object.defineProperty(), and the property of the object can be controlled more precisely by the setting of the descriptor.

Object.defineProperty(obj, variate, {
                enumerable:true, //Controls whether the property can be enumerated, the default value is false
                 //writable:true, //Whether the control property can be modified, the default value is false
                 configurable:true, //Control whether the property can be deleted, the default value is false
                set: function (value) {
                    console.log('global set value!');
                    val = value; 
                    const data = {};
                    data[variate] = value;
                    console.log('page set value!');
                    page.setData(data);
                },
                get: function () {
                    console.log('global get value!');
                    // This will be executed when getApp().globalData.variate is called in other interfaces.
                     return val; // return the current value
                }
            });

Finally, there are two most important attributes, set and get (that is, accessor Description: define how attributes are accessed). What are these two attributes used for?

Note: when getter or setter methods are used, writable and value attributes are not allowed (if used, an error will be reported directly)

5. Solution

This error is caused by the value of configurable being set to false, so it can be changed to true! Pay attention to the error prompt on the console. Maybe your error is reported in other situations!

Read More: