如何解决此错误:
core.js:1449错误错误:未捕获(按承诺):TypeError:无法 读取未定义TypeError的属性'slug':无法读取属性 未定义的“子弹”
我的代码:
this.setState({x: JSON.parse(walletdata),y: JSON.stringify(walletdata.x)},()=>{
console.log("output: "+ this.state.y);
console.log("output y:"+JSON.parse(this.state.y.isloggedIn));
});
答案 0 :(得分:1)
对我来说,这证实了我首先说的话。您确实是在指向可观察对象内的对象的子对象(无论您是否知道可观察对象)(可观察对象有时会一直移至优先级列表的上方,并在其他变量变水之前发生。)
所以这是我要采取的预防措施,以确保事情进展顺利:将事情分解。
此外,这是我通常会使用的“ hack”,以确保我可以不受阻碍地继续开发周期,并且除了“ undefined”以外,还可以更好地了解发生故障的地方:
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
内部的水化。
希望这会有所帮助! :)