【问题标题】:Uncaught (in promise) TypeError: Cannot set property of undefined with axiosUncaught (in promise) TypeError: Cannot set property of undefined with axios
【发布时间】:2018-01-26 08:35:22
【问题描述】:

我有这个 vue.js 组件,它使用 axios 检索 joke 对象的 json 数组:

<template>
  <div id="show-jokes-all">
        <h2>Showing all jokes</h2>
        <div v-for="joke in jokes">
                <h2>{{joke.title}}</h2>
                <article>{{joke.body}}</article>
            <hr>
        </div>  

  </div>
</template>

<script>
import axios from 'axios';

    export default {
        name: 'showJokes',

      data () {
        return {
            jokes:[]

        }
      },

      methods: {

      },

      created() {
        axios.get('http://127.0.0.1:8090/api/jokes).then(function(data){    
       //console.log(data); works fine
        this.jokes = data.body;
        });
    }
}
</script>

当我在控制台中记录结果时很好,但是当我尝试将它放入 jokes 数组时,我得到了

Uncaught (in promise) TypeError: Cannot set property 'jokes' of 未定义

这可能是一个微不足道的错误,但作为 vue.js 的新手,我对此很了解,因此感谢您的提示。

【问题讨论】:

  • 本质上是.then(data =&gt; this.jokes = data.body),而不是你拥有的功能。或者使用上面链接中描述的闭包或绑定。
  • @Bert,我按照本教程进行操作,这就是它使用数据的方式:youtu.be/aoWqFLGCK60?list=PL4cUxeGkcC9gQcYgjhBoeQH7wiAyZNrYa
  • 该教程使用 VueResource (this.$http) 而不是 axiosthis 在这两个库的回调中被区别对待。
  • 对任何未来读者的澄清;我上面说的是.then(data =&gt; this.jokes = data.body),但应该是.then(response =&gt; this.jokes = response.data)

标签: javascript vue.js axios


【解决方案1】:

您已脱离this 上下文。您应该将 this 上下文存储在变量中。

 created() {
    let self = this
    axios.get('http://127.0.0.1:8090/api/jokes').then(function(data){    
   //console.log(data); works fine
    self.jokes = data.body;
    });
}

How to access the correct this inside a callback? 有很多方法。您可以参考这里的多种方式。

感谢 Bert on cmets

【讨论】:

  • 现在是 2018 年,无需再使用 let self = this 了 :) 改用 arrow functionaxios.get('http://127.0.0.1:8090/api/jokes').then(data =&gt; { ... });
【解决方案2】:

是的,你可以使用 ES6。

<template>
    <div id="show-jokes-all">
        <h2>Showing all jokes</h2>
        <div v-for="joke in jokes">
            <h2>{{joke.title}}</h2>
            <article>{{joke.body}}</article>
            <hr>
        </div>  
    </div>
</template>

<script>
import axios from 'axios';
  export default {
    name: 'showJokes',
    data () {
      return {
        jokes:[]
      }
    },
    methods: {
    },
    created() {
      axios.get('http://127.0.0.1:8090/api/jokes').then((data) => {    
      // console.log(data); // works fine
      this.jokes = data.body;
    });
  }
}
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2019-02-12
    • 2021-09-20
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多