无法将 axios 响应传输到对象 [重复]

Posted

技术标签:

【中文标题】无法将 axios 响应传输到对象 [重复]【英文标题】:Unable to transfer an axios response to a object [duplicate] 【发布时间】:2021-01-14 11:42:57 【问题描述】:

我正在尝试将响应的结果传输到字符对象,但它会引发错误:

无法读取未定义的属性“字符”

<script>
const axios = require("axios");
export default 
  data: () => (
    characters:[],
  ),
  created() 
    axios
      .get("https://rickandmortyapi.com/api/character")
      .then(function(response) 
        const resp = response.data.results;
        this.characters.push(resp);
      )
      .catch(function(error) 
        // handle error
        console.log(error);
      );
    
  ,
;
</script>

【问题讨论】:

等一下……对象上根本没有 characters 属性,只有一个在调用 data 方法时按需生成的属性。 characters 在另一个函数的主体中定义。你到底想达到什么目的? 【参考方案1】:

this 不是指你的 vue 实例,所以有一些方法可以解决它

方案一箭头函数

    axios
      .get("https://rickandmortyapi.com/api/character")
      .then(response => 
        const resp = response.data.results;
        this.characters.push(resp);
      )
      .catch(error => 
        // handle error
        console.log(error);
      );

或者绑定

    axios
      .get("https://rickandmortyapi.com/api/character")
      .then(function(response) 
        const resp = response.data.results;
        this.characters.push(resp);
      .bind(this))
      .catch(function(error) 
        // handle error
        console.log(error);
      .bind(this));

或者你选择异步/等待

async created() 
  try 
     let  data  = await axios.get("https://rickandmortyapi.com/api/character")
     this.characters.push(data.results);
   catch(err) 
     console.log(err)
  
,

【讨论】:

以上是关于无法将 axios 响应传输到对象 [重复]的主要内容,如果未能解决你的问题,请参考以下文章