Skip to content

TypeError: Cannot assign to read only property

Error message

                Cannot assign to read only property 'x' of object '#<Object>'
              

Quick summary

You tried to assign a value to a property that is read-only — the object was frozen or the property was defined as non-writable.

Why this happens

  • The object was frozen with Object.freeze()

  • The property was defined with writable: false using Object.defineProperty()

  • You are trying to modify a property of a built-in immutable object

Minimal example

✗ Broken code
const obj = Object.freeze({ x: 1 });
obj.x = 2;
✓ Fixed code
const obj = Object.freeze({ x: 1 });
const updated = { ...obj, x: 2 };

Frozen objects cannot be mutated. Create a new object with the updated property using spread.

How to diagnose

  • Check if the object was passed through Object.freeze()

  • Use Object.getOwnPropertyDescriptor() to check if the property is writable

  • Verify the object is not a built-in frozen object

How to fix

  • Create a copy of the object and modify the copy instead

  • Remove the Object.freeze() call if mutation is intended

  • Use Object.defineProperty to redefine the property as writable

How to prevent

  • Document which objects are frozen and should not be mutated

  • Use spread to create modified copies instead of mutating frozen objects

Related Resources

Related Glossary

Related Lessons

  • Objects

    Learn about object immutability.

← Back to language