uni-app 3.3.13以后版本编译视图层renderjs代码时调用任意对象方法报错(误报)

发布于 1周前 作者 ionicwang 来自 Uni-App

uni-app 3.3.13以后版本编译视图层renderjs代码时调用任意对象方法报错(误报)

产品分类 PC开发环境操作系统 PC开发环境操作系统版本号 HBuilderX版本号
HbuilderX Windows windows 11 3.4.7

产品分类:HbuilderX
PC开发环境操作系统:Windows
PC开发环境操作系统版本号:windows 11
HBuilderX版本号:3.4.7

示例代码:

<template>  
    <view class="content">  
        <!-- #ifdef APP-PLUS || H5 -->  
        <view @click="echarts.onClick" :prop="option" :change:prop="echarts.updateEcharts" id="echarts" class="echarts"></view>  
        <button @click="changeOption">更新数据</button>  
        <!-- #endif -->  
        <!-- #ifndef APP-PLUS || H5 -->  
        <view>非 APP、H5 环境不支持</view>  
        <!-- #endif -->  
    </view>  
</template>  

<script>  
    export default {  
        data() {  
            return {  
                option: {  
                    title: {  
                        text: 'ECharts 入门示例'  
                    },  
                    tooltip: {},  
                    legend: {  
                        data: ['销量']  
                    },  
                    xAxis: {  
                        data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]  
                    },  
                    yAxis: {},  
                    series: [{  
                        name: '销量',  
                        type: 'bar',  
                        data: [5, 20, 36, 10, 10, 20]  
                    }]  
                }  
            }  
        },  
        onLoad() {  

        },  
        methods: {  
            changeOption() {  
                const data = this.option.series[0].data  
                // 随机更新示例数据  
                data.forEach((item, index) => {  
                    data.splice(index, 1, Math.random() * 40)  
                })  
            },  
            onViewClick(options) {  
                console.log(options)  
            }  
        }  
    }  
</script>  

<script module="echarts" lang="renderjs">  
    let myChart  
    export default {  
        mounted() {  
            if (typeof window.echarts === 'function') {  
                this.initEcharts()  
            } else {  
                // 动态引入较大类库避免影响页面展示  
                const script = document.createElement('script')  
                // view 层的页面运行在 www 根目录,其相对路径相对于 www 计算  
                script.src = 'static/echarts.js'  
                script.onload = this.initEcharts.bind(this)  
                document.head.appendChild(script)  
            }  
        },  
        methods: {  
            initEcharts() {  
                myChart = echarts.init(document.getElementById('echarts'))  
                // 观测更新的数据在 view 层可以直接访问到  
                myChart.setOption(this.option)  
            },  
            updateEcharts(newValue, oldValue, ownerInstance, instance) {  
                // 监听 service 层数据变更  
                myChart.setOption(newValue)  
            },  
            onClick(event, ownerInstance) {  
                // 调用 service 层的方法  
                ownerInstance.callMethod('onViewClick', {  
                    test: 'test'  
                })  
            }  
        }  
    }  
</script>  

<style>  
    .content {  
        display: flex;  
        flex-direction: column;  
        align-items: center;  
        justify-content: center;  
    }  

    .echarts {  
        margin-top: 100px;  
        width: 100%;  
        height: 300px;  
    }  
</style>  

## 操作步骤:


```html
<template>  
    <view class="content">  
        <!-- #ifdef APP-PLUS || H5 -->  
        <view @click="echarts.onClick" :prop="option" :change:prop="echarts.updateEcharts" id="echarts" class="echarts"></view>  
        <button @click="changeOption">更新数据</button>  
        <!-- #endif -->  
        <!-- #ifndef APP-PLUS || H5 -->  
        <view>非 APP、H5 环境不支持</view>  
        <!-- #endif -->  
    </view>  
</template>  

<script>  
    export default {  
        data() {  
            return {  
                option: {  
                    title: {  
                        text: 'ECharts 入门示例'  
                    },  
                    tooltip: {},  
                    legend: {  
                        data: ['销量']  
                    },  
                    xAxis: {  
                        data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]  
                    },  
                    yAxis: {},  
                    series: [{  
                        name: '销量',  
                        type: 'bar',  
                        data: [5, 20, 36, 10, 10, 20]  
                    }]  
                }  
            }  
        },  
        onLoad() {  

        },  
        methods: {  
            changeOption() {  
                const data = this.option.series[0].data  
                // 随机更新示例数据  
                data.forEach((item, index) => {  
                    data.splice(index, 1, Math.random() * 40)  
                })  
            },  
            onViewClick(options) {  
                console.log(options)  
            }  
        }  
    }  
</script>  

<script module="echarts" lang="renderjs">  
    let myChart  
    export default {  
        mounted() {  
            if (typeof window.echarts === 'function') {  
                this.initEcharts()  
            } else {  
                // 动态引入较大类库避免影响页面展示  
                const script = document.createElement('script')  
                // view 层的页面运行在 www 根目录,其相对路径相对于 www 计算  
                script.src = 'static/echarts.js'  
                script.onload = this.initEcharts.bind(this)  
                document.head.appendChild(script)  
            }  
        },  
        methods: {  
            initEcharts() {  
                myChart = echarts.init(document.getElementById('echarts'))  
                // 观测更新的数据在 view 层可以直接访问到  
                myChart.setOption(this.option)  
            },  
            updateEcharts(newValue, oldValue, ownerInstance, instance) {  
                // 监听 service 层数据变更  
                myChart.setOption(newValue)  
            },  
            onClick(event, ownerInstance) {  
                // 调用 service 层的方法  
                ownerInstance.callMethod('onViewClick', {  
                    test: 'test'  
                })  
            }  
        }  
    }  
</script>  

<style>  
    .content {  
        display: flex;  
        flex-direction: column;  
        align-items: center;  
        justify-content: center;  
    }  

    .echarts {  
        margin-top: 100px;  
        width: 100%;  
        height: 300px;  
    }  
</style>  

## 预期结果:


无错误

实际结果:

10:45:00.407 项目 ‘renderjs-echarts-demo’ 开始编译… 10:45:03.321 请注意运行模式下,因日志输出、sourcemap以及未压缩源码等原因,性能和包体积,均不及发行模式。 10:45:03.633 正在编译中… 10:45:05.766 INFO Starting development server… 10:45:20.554 App running at: 10:45:20.554 - Local: http://localhost:8080/ 10:45:20.557 - Network: http://192.168.1.7:8080/ 10:45:20.558 项目 ‘renderjs-echarts-demo’ 编译成功。前端运行日志,请另行在浏览器的控制台查看。 10:45:20.559 H5版常见问题参考: https://ask.dcloud.net.cn/article/35232 10:45:24.223 [HMR] Waiting for update signal from WDS… 10:45:24.450 App Launch at App.vue:4 10:45:24.452 App Show at App.vue:7 10:45:24.479 [Vue warn]: Error in callback for immediate watcher “option”: “TypeError: Cannot read property ‘setOption’ of undefined” found in —> at pages/index/index.vue 10:45:24.485 [system]TypeError: Cannot read property ‘setOption’ of undefined at VueComponent.updateEcharts (webpack-internal:///qZC/:23:15) at VueComponent.vnode.$wxsWatches.(anonymous function).oldWxsWatches.(anonymous function).vnode.context.$watch.immediate (http://localhost:8080/static/js/chunk-vendors.js:8478:21) at VueComponent.Vue.$watch (http://localhost:8080/static/js/chunk-vendors.js:6693:12) at http://localhost:8080/static/js/chunk-vendors.js:8477:68 at Array.forEach (<anonymous>) at Array.updateWxsProps (http://localhost:8080/static/js/chunk-vendors.js:8470:25) at invokeCreateHooks (http://localhost:8080/static/js/chunk-vendors.js:7811:22) at initComponent (http://localhost:8080/static/js/chunk-vendors.js:7744:7) at createComponent (http://localhost:8080/static/js/chunk-vendors.js:7727:9) at createElm (http://localhost:8080/static/js/chunk-vendors.js:7667:9)


4 回复

不是BUG,我从VUE2过渡到VUE3,renderjs有点变化,每次刷新页面都会主动触发renderjs中的方法,所以会报错,只要给传参加个判断就好了。

在 uni-app 3.3.13 及以后的版本中,编译视图层 renderjs 代码时,调用任意对象方法可能会遇到误报错误。这通常是由于编译器的严格模式或某些静态分析工具的误判导致的。以下是一些可能的解决方案和排查步骤:

1. 检查代码语法

确保你的 renderjs 代码语法正确,没有拼写错误或语法错误。特别是检查对象方法的调用方式是否正确。

2. 使用 try-catch 捕获异常

在调用对象方法时,使用 try-catch 语句捕获可能的异常,避免程序崩溃。

try {
    obj.method();
} catch (e) {
    console.error('Error calling method:', e);
}

3. 检查对象是否存在

在调用对象方法之前,确保对象已经正确初始化,并且不为 nullundefined

if (obj && typeof obj.method === 'function') {
    obj.method();
}

4. 使用 evalFunction 动态调用方法

如果编译器误报错误,可以尝试使用 evalFunction 动态调用方法。不过,这种方法需要谨慎使用,因为它可能会带来安全风险。

const methodName = 'method';
if (obj && typeof obj[methodName] === 'function') {
    obj[methodName]();
}

5. 更新 uni-app 版本

确保你使用的是最新版本的 uni-app,因为新版本可能已经修复了相关的问题。

npm update @dcloudio/uni-app

6. 检查编译配置

检查你的项目编译配置,确保没有启用过于严格的静态分析工具或编译选项。

7. 反馈给官方

如果以上方法都无法解决问题,建议将问题反馈给 uni-app 官方团队,提供详细的错误信息和代码示例,以便他们进行排查和修复。

示例代码

以下是一个简单的示例,展示了如何在 renderjs 中安全地调用对象方法:

export default {
    methods: {
        callMethod() {
            const obj = {
                method() {
                    console.log('Method called');
                }
            };

            if (obj && typeof obj.method === 'function') {
                try {
                    obj.method();
                } catch (e) {
                    console.error('Error calling method:', e);
                }
            }
        }
    }
};
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!