【快应用】快应用赋值时出现堆栈溢出

 

现象描述

将通过 $element('id') 获取到内容,赋值给成员变量,引发堆栈溢出(RangeError: Maximum call stack size exceeded),从而导致程序的崩溃。页面成员变量stateText发生变化时,也引发堆栈溢出的报错。

错误示例代码如下:

<template>

<div id="content">

<input type="button" class="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属性,会触发大规模的数据驱动变化,导致内部出现异常循环,从而引发堆栈溢出的错误。

解决方法

请勿对成员变量进行赋值,如果需要赋值,可以赋值给局部变量或者页面的全局变量。

正确的示例代码如下:

<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/consumer/cn/forum/?ha_source=zzh

posted @ 2023-02-13 10:04  华为开发者论坛  阅读(19)  评论(0编辑  收藏  举报