'How to fix Uncaught (in promise) TypeError: Cannot set property of undefined

I get an error when I want to send the value from the API results to the data, the error is like this

Uncaught (in promise) TypeError: Cannot set property 'notification' of undefined at eval (HeaderPortal.vue?070f:367)

this my HeaderPortal.vue

    data() {
      return {
        notification: []
      }
    }
    methods: {
        const res = this.GET('/api/v2/notification', 'BEARER', null).then( function(res) {
          console.log(JSON.parse(res))
          this.notification = JSON.parse(res);
        });
    }

this.GET comes from here

methods: {
        async GET(url, headers, callback) {
            const options = headers === 'BASIC' ? HEADERS_BASIC : HEADERS_BEARER;
            try {
                const response = await axios.get(`${BASE_URL}${url}`, options);
                return (JSON.stringify(response));
            } catch (e) {
                console.error(e);
            }
        },
}

how to handle it? is there something wrong in my code?



Solution 1:[1]

answer up is low clear , let me show what do with example :

data() {
      return {
        notification: []
      }
    }
    methods: {
        const res = this.GET('/api/v2/notification', 'BEARER', null).then( res =>  {
          console.log(JSON.parse(res))
          this.notification = JSON.parse(res);
        });
    }

i hope be useful

Solution 2:[2]

this in the inner function refers to the function only, therefore it is not working. Instead, write:

s=this;
const res = this.GET('/api/v2/notification', 'BEARER', null).then( 
function(res) {
      console.log(JSON.parse(res))
      s.notification = JSON.parse(res);
    });
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 salvo720
Solution 2 Mark Rotteveel