Symptom
It is known that if the content obtained by $element('id') is assigned to a member variable, it may cause a stack overflow (RangeError: Maximum call stack size exceeded), causing the program to crash; at the same time, there are member variables in the page DOM (such as A ), when the variable A changes, it will cause a stack overflow error. The sample code is as follows:

<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>

This is because assigning a value to the vm attribute will trigger large-scale data-driven changes, resulting in an internal abnormal loop, which will cause a stack overflow error.

Solution
As long as you don't get the content of $element('id') and assign it to a member variable, you can avoid the stack overflow problem; you can assign it to a local variable or a page global variable. The sample code is as follows:

<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>

Original link: https://developer.huawei.com/consumer/cn/forum/topic/0204465500063450107?fid=0101271690375130218
Original Author: Mayism


华为开发者论坛
352 声望56 粉丝

华为开发者论坛是一个为开发者提供信息传播、开发交流、技术分享的交流空间。开发者可以在此获取技术干货、华为源码开放、HMS最新活动等信息,欢迎大家来交流分享!


引用和评论

0 条评论