2

I have a Vue 2 application with a state variable (an array of box objects) called boxes. I have a computed property which extracts a subset of these boxes (nearest_box_linked_boxes).

I have a method which iterates through the boxes returned by nearest_box_linked_boxes, and changes the value of a property in each element:

for(let i=0;i<this.nearest_box_linked_boxes.length;i++)
{
  let box = this.nearest_box_linked_boxes[i];
  box.object_class = this.$store.state.selected_object_class;
  box.patch();
}

This method is returning an error:

vue.esm.js:648 [Vue warn]: Error in v-on handler: "TypeError: Cannot assign to read only property 'object_class' of object '#<Box>'"

I never explicitly made any of the box objects (or their properties) read-only. I do understand that I can't write to nearest_box_linked_boxes (the parent array object) because it's a calculated property, but I thought it should be possible to modify properties of each element in this array.

Am I running into an issue caused by Vue and calculated properties here, or something else?

2 Answers 2

5

You should always treat computed properties as “read-only”, the exception being computed setters.

While its technically possible to mutate an object returned by a computed properties, it’s generally bad idea. The object will be replaced as soon as a dependency changes, and your changes would be lost.

1
  • 1
    My mistake - it turns out I did call Object.freeze, and I had just forgotten about it. Anyway, thanks for the help. I will probably delete this question.
    – afarley
    Commented Sep 15, 2021 at 20:17
2

This turned out to be my own mistake. Nikola's response is probably good practice, but I was actually calling Object.freeze at some point in my code and I had forgotten about it. This was not a side-effect of anything related to Vue or anything really mysterious at all.

Not the answer you're looking for? Browse other questions tagged or ask your own question.