如何找出反应本机应用程序中的内存泄漏?

Lin*_*rin 12 javascript memory-leaks memory-management reactjs react-native

我已经在 react native android 中构建了一个学习管理系统应用程序。我AsyncStorage用于简单的状态管理,而根本没有使用 redux。我现在面临的问题是,如果我要通过执行不同的操作来连续使用该应用程序操作然后应用程序变得非常慢。我认为这是内存泄漏,因为当我从后台杀死应用程序并再次打开它时,它没有任何延迟地工作。所以我不知道如何避免这种内存泄漏。我试过了许多解决方案

  1. console.log从应用程序中删除了所有内容
  2. 更改了所有内联样式
  3. 使用ComponentDidMount代替ComponentWillMount
  4. 尝试预取数据。

但我不知道如何从堆内存中删除数据。数据是否存储在heap每个导航中?所以这会使应用程序的性能非常慢。不知道我说的对不对。如果我的概念有任何错误,redux请见谅。现在没有时间更改状态管理。请任何人帮助我找到解决方案,这将是一个很大的帮助。谢谢!

小智 9

我遇到了同样的问题,一些有帮助的方法是:

使用转换删除控制台:

https://www.npmjs.com/package/babel-plugin-transform-remove-console

将此添加到您的 babel 生产插件并安装它。它将隐藏生产中应用程序中的所有控制台日志。

添加挂载状态

具体来说,在卸载的组件中调用 setState() 意味着您的应用程序在卸载组件后仍然持有对该组件的引用 - 这通常表示内存泄漏!

https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html

import React, { Component } from 'react';


class App extends Component {

  _isMounted = false;

  componentDidMount() {
    this._isMounted = true;
    // ... do your stuff here
  }

  componentWillUnmount() {
    // tells the component that component is now unmounted
    this._isMounted = false;
  }

  getUsersFromApi(){
    if(this._isMounted){
      // ... tasks
    }
  }

}

export default App;
Run Code Online (Sandbox Code Playgroud)

  • 这两种方法我都试过了,但反应还是一样 (3认同)

Hen*_*hli 5

我也有同样的问题,因为调用setState了一个未安装的组件,

所以,我通常为任何具有状态的基于类的组件使用这个模板:

我忘了setState(),并使用setComponentState声明下来:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      // other fields...

    };
    this.isUnmounted =  true,
  }

  componentDidMount(){
      this.isUnmounted =  false;
  }

  componentWillUnmount() {
      this.isUnmounted = true;
  }

  setComponentState = (values) => {
    if (!this.isUnmounted) this.setState(values);
  };
}
Run Code Online (Sandbox Code Playgroud)