简体   繁体   English

React Ajax setInterval内存泄漏

[英]React Ajax setInterval Memory leak

I looked and tried everything in the other questions. 我查看并尝试了其他所有问题。 Still couldn't solve my memory leak. 仍然无法解决我的内存泄漏。 Here's the code. 这是代码。 Essentially it gets a JSON file from a server and updates the table accordingly. 本质上,它从服务器获取JSON文件并相应地更新表。 It loops the AJAX call every 5 seconds. 它每5秒钟循环一次AJAX调用。

Memory leak happens in this AJAX call. 内存泄漏发生在此AJAX调用中。 Any help would be great. 任何帮助都会很棒。

LoadDataTable: function(){ LoadDataTable:function(){

 $.ajax({
  url: "***************************.json",
  dataType: 'json',
  cache: false,
  timeout: 5000,
  success: function(data) { 
   this.setState({temp1:data[2].field3}),
   this.setState({temp2:data[2].field5}),
   this.setState({temp3:data[2].field25}),
   this.setState({temp4:data[2].field26});

     if(data[2].field3 > 9 || data[2].field5 >9||data[2].field5>9 ||data[2].field26>9){
        document.location.href='#/'
   }
   else{
       //console.log("Stopped playing");
   }
   setTimeout(this.LoadDataTable, 5000);


}.bind(this),
  error: function(request, status, err) {

    //request.abort();
    console.log(request);
    setTimeout(this.LoadDataTable, 5000);

  }.bind(this),

 })

},
componentDidMount: function() {
    this.LoadDataTable();
    //this.setInterval(this.LoadDataTable, 100);// Call a method on the mixin
},

Try moving your success and error functions out to a named function like this: 尝试将成功和错误功能移到这样的命名函数中:

$.ajax({
  url: "***************************.json",
  dataType: 'json',
  cache: false,
  timeout: 5000,
  success: this.successTimeout,
  error: this.errorTimeout,
})

componentDidMount: function() {
  this.LoadDataTable();
  //this.setInterval(this.LoadDataTable, 100);// Call a method on the mixin
},

successTimeout(data) { 
  this.setState({temp1:data[2].field3}),
  this.setState({temp2:data[2].field5}),
  this.setState({temp3:data[2].field25}),
  this.setState({temp4:data[2].field26});

  if(data[2].field3 > 9 || data[2].field5 >9||data[2].field5>9 ||data[2].field26>9){
     document.location.href='#/'
  }
  else{
    //console.log("Stopped playing");
  }

  setTimeout(this.LoadDataTable, 5000);
}.bind(this),

errorTimeout(request, status, err) {
  //request.abort();
  console.log(request);
  setTimeout(this.LoadDataTable, 5000);
}.bind(this)

Also, you might want to think about using the fetch API . 另外,您可能要考虑使用fetch API Just be sure to include the polyfill for browser compatibility 只要确保包含polyfill即可实现浏览器兼容性

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM