8

如何解决快应用堆栈溢出问题

 3 years ago
source link: https://segmentfault.com/a/1190000040426891
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何解决快应用堆栈溢出问题

现象描述
已知将通过 $element('id') 获取到内容,赋值给成员变量,可能会引发堆栈溢出(RangeError: Maximum call stack size exceeded),从而导致程序崩溃;同时,页面 DOM 存在成员变量(如 A )的引用,当该变量 A 发生变化时,即会引发堆栈溢出报错问题,示例代码如下:

<template>
  <div id="content">
    <input type="button" @click="onTestClick" value="会引发堆栈溢出"/>
    <text>{{ stateText }}</text>
  </div>
</template>
<script>
  export default {
    private: {
      mContentNode: null,
      stateText: 'init state'
    },
    onReady() {
      /* 如将 $element('id')获取到内容,赋值给成员变量,则有可能引发堆栈溢出 */
      this.mContentNode = this.$element('content')
    },
    onTestClick() {
      /* 页面 DOM 存在成员变量的引用,当发生变化时,即是引发如上所述的一种必现方式 */
      this.stateText = 'new state'
    }
  }
</script>

这是因为赋值为 vm 属性,会触发大规模的数据驱动变化,导致内部出现异常循环,从而引发堆栈溢出报错。

解决方法
只要不将 $element('id') 获取到内容,赋值给成员变量,即可规避堆栈溢出问题;可以将其赋值给局部变量,或页面全局变量,示例代码如下:

<script>
  let $gContentNode = null
  export default {
    private: {
      stateText: 'init state'
    },
    onReady() {
      /* 如将 $element('id')获取到内容,赋值给局部变量,或页面全局变量,则可规避堆栈溢出问题 */
      const cContentNode = this.$element('content')
      $gContentNode = this.$element('content')
    },
    onTestClick() {
      this.stateText = 'new state'
    }
  }
</script>

原文链接:https://developer.huawei.com/...
原作者:Mayism


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK