Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法读取属性';长度';未定义的…尽管对象已定义_Javascript - Fatal编程技术网

Javascript 无法读取属性';长度';未定义的…尽管对象已定义

Javascript 无法读取属性';长度';未定义的…尽管对象已定义,javascript,Javascript,首先,我有以下代码部分: export default class Recipe { constructor(recID) { this.RecipeID = recID; } async GetRecipe() { try { let Result = await Axios( `https://forkify-api.herokuapp.com/api/get?rId=${this.RecipeID}` );

首先,我有以下代码部分:

export default class Recipe {
  constructor(recID) {
    this.RecipeID = recID;
  }

  async GetRecipe() {
    try {
      let Result = await Axios(
        `https://forkify-api.herokuapp.com/api/get?rId=${this.RecipeID}`
      );
      this.Tilte = Result.data.recipe.title;
      this.Author = Result.data.recipe.publisher;
      this.Image = Result.data.recipe.image_url;
      this.Url = Result.data.recipe.source_url;
      this.Ingredients = Result.data.recipe.ingredients;
      this.PublisherUrl = Result.data.recipe.publisher_url;
      this.Rank = Result.data.recipe.social_rank;
    } catch (error) {
      alert(error);
    }
  }

  CalculateTime() {
    try {
      this.Time = Math.ceil(this.Ingredients.length / 3) * 15; // error is here
    } catch (error) {
      console.log(this.RecipeID + ": Length Error->"+error);
    }
  }
}
然后在单独的文件中调用上述代码,如:

import Recipe from "./Recipe";

const RecipeController = async () => {
  const ID = window.location.hash.replace("#", "");

  if (ID) {
    AppState.Recipe = new Recipe(ID);

    try {
      await AppState.Recipe.GetRecipe();

      AppState.Recipe.CalculateTime();

      console.log(AppState.Recipe);
    } catch (error) {
      alert(error);
    }
  }
};
现在,如下图所示,我确实得到了请求的响应&承诺已得到解决,加上“配料”数组中有元素,但有时在调用“CalculateTime()时仍会出现错误“无法读取未定义的属性'length'”'虽然现在已经定义了数组,而且有时我没有收到任何错误&它工作得非常好。为什么会出现这种随机行为?即使是JSON响应中的id&我记录的错误也与之匹配,即47746。

你确定一些回答没有遗漏成分吗?计算时间总是在getRecipe之后调用

我会添加一个条件或回退来防止错误,如中所示

 this.Time = Math.ceil((this.Ingredients || []).length / 3) * 15; 

这就是为什么有太多的
try
/
catch
es会掩盖错误的原因,从而导致调试困难的原因之一。问题可以归结为以下几点:

类配方{
构造函数(recID){
this.RecipeID=recID;
}
异步GetRecipe(){
让结果=等待获取(
`https://forkify-api.herokuapp.com/api/get?rId=47746`
)。然后(res=>res.json());

console.log(Result);//我推测这种“随机”行为可能与异步代码有关。在计算之前,您需要确保类具有适当的成分。我觉得您应该尝试使用
.then()
.catch()将语法更改为
,尤其是因为您已经在代码中使用了
try/catch
。这种方法将确保正确解析axios请求的承诺,并消除“随机性”,因为您可以更好地控制承诺处理的不同阶段

let Result = await Axios(
        `https://forkify-api.herokuapp.com/api/get?rId=${this.RecipeID}`
       )
       .then((data) => {
           this.Tilte = data.data.recipe.title;
           this.Author = data.data.recipe.publisher;
           this.Image = data.data.recipe.image_url;
           this.Url = data.data.recipe.source_url;
           this.Ingredients = data.data.recipe.ingredients;
           this.PublisherUrl = data.data.recipe.publisher_url;
           this.Rank = data.data.recipe.social_rank;
           this.Ingerdients = data.data.recipe.ingredient;
       }
       .catch((err) => {
           console.log(err);
           return null;
       });
console.log(Result.data.recipe.components)
添加到
GetRecipe()