Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

nuxt.js - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you need to access the this keyword, make sure you use arrow functions () => {} instead of regular functions function() {} in your callback. If you don't, the this keyword will be undefined in your case. This is why you get an error trying to set this.notification = JSON.parse(res); in your first code snippet.

Your first code snippet is a bit weird, maybe you forgot to copy something? You code should not be directly inside the methods object. It should be in the mounted hook, or in a proper method like in the second snippet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...