How to fix the ‘Uncaught (in promise) TypeError: Cannot set property ‘message’ of undefined’ in Vue.js?

Sometimes, we want to fix the ‘Uncaught (in promise) TypeError: Cannot set property ‘message’ of undefined’ in Vue.js.

In this article, we’ll look at how to fix the ‘Uncaught (in promise) TypeError: Cannot set property ‘message’ of undefined’ in Vue.js.

How to fix the ‘Uncaught (in promise) TypeError: Cannot set property ‘message’ of undefined’ in Vue.js?

To fix the ‘Uncaught (in promise) TypeError: Cannot set property ‘message’ of undefined’ in Vue.js, we should make sure we aren’t referencing properties of undefined values in our methods.

For instance, we write

<script>
//...
export default {
  //...
  async loadData() {
    const response = await this.$http.get("/notifications");
    this.message = response.data;
    console.log(this.message);
  },
  //...
};
</script>

to add the loadData method which references the response.data property.

To avoid the error, we should make sure that response is an object before referencing response.data.

To do this, we can replace the . with the optional chaining operator by writing

response?.data

instead of response.data.

Conclusion

To fix the ‘Uncaught (in promise) TypeError: Cannot set property ‘message’ of undefined’ in Vue.js, we should make sure we aren’t referencing properties of undefined values in our methods.