0
0
VueDebug / FixBeginner · 4 min read

How to Fix 'Computed Property Was Assigned' Error in Vue

In Vue, computed properties are read-only by default and cannot be assigned values directly. To fix the error, avoid assigning to a computed property and instead update the underlying reactive data or use a computed setter if you need two-way binding.
🔍

Why This Happens

Vue's computed properties are designed to automatically calculate values based on reactive data. They are read-only by default, so trying to assign a value directly to a computed property causes an error. This happens because computed properties are like formulas, not variables you can set.

javascript
export default {
  data() {
    return {
      count: 0
    };
  },
  computed: {
    doubleCount() {
      return this.count * 2;
    }
  },
  methods: {
    updateDouble() {
      this.doubleCount = 10; // ❌ This causes the error
    }
  }
};
Output
Error: "Computed property 'doubleCount' was assigned to but it has no setter."
🔧

The Fix

Instead of assigning a value directly to a computed property, update the reactive data it depends on. If you want to assign to a computed property, define a setter function inside the computed property to handle the assignment properly.

javascript
export default {
  data() {
    return {
      count: 0
    };
  },
  computed: {
    doubleCount: {
      get() {
        return this.count * 2;
      },
      set(value) {
        this.count = value / 2;
      }
    }
  },
  methods: {
    updateDouble() {
      this.doubleCount = 10; // ✅ This updates count to 5
    }
  }
};
Output
When updateDouble() runs, count becomes 5 and doubleCount returns 10.
🛡️

Prevention

Always treat computed properties as read-only unless you explicitly define a setter. Use reactive data or ref variables for values you want to change directly. Enable linting rules like vue/no-mutating-props to catch improper assignments early.

Follow these best practices:

  • Use computed getters for derived state.
  • Use setters only when two-way binding is needed.
  • Update underlying data, not computed properties, in methods.
⚠️

Related Errors

Other common Vue errors related to computed properties include:

  • "Computed property has no getter": Happens if you define a computed property without a return value.
  • "Avoid mutating a prop directly": Occurs when trying to assign a value to a prop instead of emitting events.

Fix these by ensuring computed properties return values and props are treated as read-only.

Key Takeaways

Computed properties in Vue are read-only by default and cannot be assigned directly.
Define a setter in computed properties to allow assignment and update underlying data.
Always update reactive data, not computed properties, to change values.
Use linting tools to catch improper computed property assignments early.
Understand the difference between data, props, and computed properties to avoid errors.