【问题标题】:How to solve Type error in an ionic framework如何解决离子框架中的类型错误
【发布时间】:2019-03-19 14:57:34
【问题描述】:

我该如何解决这个错误:

core.js:1449 ERROR 错误:未捕获(承诺):TypeError:不能 读取未定义类型错误的属性“slug”:无法读取属性 未定义的“蛞蝓”

我的代码:

this.WooCommerce.getAsync("products?filter[category]=" + this.category.slug).then((data) =>{
  console.log(JSON.parse(data.body));

【问题讨论】:

  • 这通常是由于指向一个变量或对象的一部分确实是undefined。这通常是一个时间框架问题。在视图的初始化处说您在任何类型的设置中说 myObject.myArray[0].slug:eval、新 var 水合、指针水合等,而有问题的对象只是一个空的未水合 var,直到您的 mySetVariableFunc() 被调用,在这种情况下它恰好是由一个本身在 init 之后触发的 observable 触发的。然后它总是会发回一个与成员身份有关的错误undefined 我不能保证这就是你所拥有的
  • 请检查我上面提到的代码请@tatsu。

标签: javascript angularjs typescript ionic-framework


【解决方案1】:

对我来说,这证实了我最初所说的话。您确实指向可观察对象中的对象的子对象(无论您是否知道可观察对象是什么)(可观察对象有时会在优先级列表中一直向上移动,并在任何其他变量的水合之前发生)。

所以我喜欢采取以下预防措施来确保事情不会变得糟糕:把事情分开。

此外,我喜欢在一般基础上使用以下“hack”,以确保我可以不受阻碍地继续我的开发周期,并更好地了解除了“未定义”之外的问题所在:

this.category['slug'];

我从来没有走这么远,但这也是允许的: this['category']['slug'];

看到这是不同的,因为它实际上会返回未定义而不是在 JS 级别失败。

现在对我来说很明显,您需要确定 this.category.slug 在被评估的那一刻它在初始化之前没有处于其生命线中的状态:

var myFunctionToLogSlug = () => { //here you could pass this.category.slug as an arg but
//that's the same as simply calling in within the body of this method because your
//context (this) is the same, ergo the pointer and timeframe are also the same.
  console.log("is this.category.slug empty ? : ", this.category.slug);
  return this.category.slug;
};

this.WooCommerce.getAsync(
   "products?filter[category]=" + myFunctionToLogSlug()).then(data =>{
       console.log(JSON.parse(data.body));
});

一旦您确定 this.category.slug 在被调用时确实未定义,您可以将 this.WooCommerce.getAsync 移动到您知道要定义的 this.category.slug 的时间地点,或者移动 this.category.slug 的水合作用到getAsync的内部。

希望这会有所帮助! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    • 2020-11-28
    • 2021-07-18
    • 2020-08-19
    • 2020-12-07
    • 1970-01-01
    相关资源
    最近更新 更多