简体   繁体   English

我为什么会收到TypeError:无法读取未定义的属性“现在”

[英]Why am I getting TypeError: Cannot read property 'now' of undefined

Why am I getting this error? 为什么会出现此错误?

relevant code: 相关代码:

this.state = {
    now: 0
}


setInterval(function () {
    this.setState({ now: this.state.now + 1});
}, 100);

I am trying to increment now in order to update a ProgressBar. 我现在尝试增加以更新ProgressBar。

Your problem is that when you reference 'this' inside the function, this is the function itself not the context outside. 您的问题是,当您在函数内部引用“ this”时,这是函数本身,而不是外部上下文。 If you are using ecmascript you can use an arrow function 如果您使用的是ecmascript,则可以使用箭头功能

this.state = {
    now: 0
}

setInterval(() =>{
    this.setState({ now: this.state.now + 1});
}, 100);

with an arrow function 'this' have a different meaning. 带有箭头功能“ this”的含义不同。

or you can create a reference outside your context, like this. 或者,您也可以像这样在上下文之外创建引用。

this.state = {
    now: 0
}

let self = this;

setInterval(function () {
    self.setState({ now: self.state.now + 1});
}, 100);

Probably when interval function runs 'this' doesn't means the same as when setInteval was called 可能当间隔函数运行时'this'的含义与调用setInteval时的含义不同

You might try something like this 您可以尝试这样的事情

this.state = {
    now: 0
}

let that = this 

setInterval(function () {
    that.setState({ now: that.state.now + 1});
}, 100);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我收到“ TypeError:无法读取未定义的属性” length” - Why am I getting 'TypeError: Cannot read property 'length' of undefined' 为什么会收到此错误类型错误:无法读取未定义的属性“客户端” - Why am getting this error TypeError: Cannot read property 'client' of undefined 为什么我收到 TypeError:无法读取未定义的属性“执行” - Why am I receiving TypeError: cannot read property 'execute' of undefined 为什么我会收到Uncaught TypeError:无法在分配时读取未定义的属性“ 0”? - why am I getting Uncaught TypeError: Cannot read property '0' of undefined on assign? 为什么会出现“ TypeError:无法读取未定义的属性” props”(反应路由器,React-Redux)? - Why am I getting 'TypeError: Cannot read property 'props' of undefined' (react-router, React-Redux)? 我为什么会收到错误:Uncaught TypeError:无法读取未定义的属性“ left” - Why am I getting the error: Uncaught TypeError: Cannot read property 'left' of undefined 为什么会出现Uncaught TypeError:无法读取未定义的属性'displayQuestion'? - Why am i getting Uncaught TypeError: Cannot read property 'displayQuestion' of undefined? 在 Firebase 中,我收到 Uncaught TypeError: Cannot read property 'initializeApp' of undefined,但不确定为什么未定义“firebase”? - In Firebase I am getting an Uncaught TypeError: Cannot read property 'initializeApp' of undefined, but not sure why 'firebase' is not defined? 为什么我得到 Uncaught (in promise) TypeError: Cannot read property 'type' of undefined? - Why am I getting Uncaught (in promise) TypeError: Cannot read property 'type' of undefined? 为什么我得到“TypeError:无法读取未定义的属性'恢复'当使用sinon.js删除mongoose时 - Why Am I getting “TypeError: Cannot read property 'restore' of undefined” when stubbing mongoose with sinon.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM