Defining arrow functions at a wrong place caused *this* object becoming undefined.

Today I was caught by a bug. I got an error message like "Uncaught (in promise) TypeError: Cannot set property 'users' of undefined" in the following code:

    import axios from 'axios';
    export default {
      name: "Users",
      data() {
          return {
            users: null
          };
      },
      created: () =>  {
        axios
          .get('https://jsonplaceholder.typicode.com/users')
          .then(res => {
            this.users = res.data;
          })
      }
    }

Finally, I figured it out by changing the created method definition from an arrow function to a normal function, the following is the correct code:

    import axios from 'axios';
    export default {
      name: "Users",
      data() {
          return {
            users: null
          };
      },
      created() {
        axios
          .get('https://jsonplaceholder.typicode.com/users')
          .then(res => {
            this.users = res.data;
          })
      }
    }

Do you see the difference?

Comments

  1. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.