TypeError: can’t define property “x”: “obj” is not extensible

Problem: In LWC, when reassigning value in cloned javascript object, you get this error.

For eg.

let weeklyReportDetailsClone = Object.assign([], this.weeklyReportDetails);
weeklyReportDetailsClone[index].isTAEditable = true;
//Any code written after this line will fail

Solution: First stringify js object and then parse it to clone as shown below-

let weeklyReportDetailsClone = JSON.parse(JSON.stringify(this.weeklyReportDetails)); //Object.assign([], this.weeklyReportDetails);<br>weeklyReportDetailsClone[index].isTAEditable = true;

Reason: The JavaScript exception “can’t define property “x”: “obj” is not extensible” occurs when Object.preventExtensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible. So stringifying and then parsing will remove Object.preventExtensions()  method.

Reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_define_property_object_not_extensible

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply