Understanding JavaScript Object Non-extensibility Errors and React State Handling Solutions

Nov 22, 2025 · Programming · 10 views · 7.8

Keywords: JavaScript | React | Non-extensible Objects | State Management | Object Copying

Abstract: This article provides an in-depth analysis of the 'object is not extensible' error in JavaScript, focusing on React state management scenarios. It explores the differences between shallow and deep copying of arrays, compares various solution approaches, and emphasizes best practices using object spread syntax for safe state modifications.

Problem Background and Error Analysis

In JavaScript development, particularly when working with state management in React, developers frequently encounter the TypeError: Cannot add property selected, object is not extensible error. This error occurs when attempting to add new properties to objects that have been marked as non-extensible.

In the original problematic code:

export const initSelect = (data) => {
    let newData = data.concat();
    newData.map((item) => {
        item.selected = false;
    })
    return newData;
}

Although data.concat() creates a shallow copy of the array, the object references within the array still point to the original objects. When these objects are marked as non-extensible by React or other libraries, direct modification triggers the error.

Mechanisms of Non-extensible Objects

JavaScript provides several methods to control object extensibility:

In strict mode, adding properties to non-extensible objects throws a TypeError, while in non-strict mode, the operation is silently ignored. React state management libraries often use these methods to ensure state immutability.

Optimal Solution

Based on the best-rated answer (score 10.0), the recommended solution is:

export const initSelect = (data) => {
 return data.map((item) => ({
     ...item,
     selected: false       
 }));
}

The key advantages of this approach include:

Alternative Approaches Comparison

The alternative solution (score 3.6) uses Object.assign:

let newData = data.map((item) => 
    Object.assign({}, item, {selected:false})
)

While this approach also solves the problem, compared to spread syntax:

Practical Application Scenarios

In React development, this pattern is particularly useful for:

By properly employing object copying techniques, developers can avoid state pollution and ensure application reliability and maintainability.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.