现象描述
已知将通过 $element('id') 获取到内容,赋值给成员变量,可能会引发堆栈溢出(RangeError: Maximum call stack size exceeded),从而导致程序崩溃;同时,页面 DOM 存在成员变量(如 A )的引用,当该变量 A 发生变化时,即会引发堆栈溢出报错问题,示例代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<
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') 获取到内容,赋值给成员变量,即可规避堆栈溢出问题;可以将其赋值给局部变量,或页面全局变量,示例代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<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