uni-app 统计2.0配置微信小程序平台导致内存耗尽崩溃

uni-app 统计2.0配置微信小程序平台导致内存耗尽崩溃

产品分类

uniapp/小程序/微信

开发环境信息

项目 详情
PC开发环境操作系统 Windows
PC开发环境操作系统版本号 win10
HBuilderX类型 Alpha
HBuilderX版本号 4.45
第三方开发者工具版本号 1.06.2501092
基础库版本号 3.7.2
项目创建方式 HBuilderX

示例代码

async onLoad(options) {
    let that = this;
    uni.hideTabBar(); //隐藏原生tabbar  
    // uni.getNetworkType({  
    //  success: function(res) {  
    //      console.log("network:", res.networkType);  
    //  }  
    // });  

    // uni.onNetworkStatusChange(this.onNetworkStatusChange)  

    // #ifdef MP-WEIXIN  
    // wx.onBackgroundFetchData(() => {  

    // })  
    wx.getBackgroundFetchData({
        fetchType: 'pre',  
        success(res) {  
            // console.log("fetchedData:",res) // 缓存数据  
            that.record = JSON.parse(res.fetchedData).data  
        },  
        fail(err){  
            console.log("err:",err)   
        }  
    })  
    // #endif  

},  
onReachBottom() { //滚动到底翻页  
    // this.$refs.udb.loadMore()  
},  
onReady() {  
    // #ifdef MP-WEIXIN  
    const windowInfo = wx.getWindowInfo()  
    this.windowWidth = windowInfo.screenWidth  
    // console.log("windowWidth:", windowInfo)  
    // #endif  
    // #ifndef MP-WEIXIN              
    uni.getSystemInfo({  
        success: (res) => {  
            let cha = res.screenWidth - 1320  
            // #ifdef H5  
            this.windowWidth = res.screenWidth - cha;  
            // #endif  
            // #ifndef H5  
            this.windowWidth = res.screenWidth  
            // #endif  

        },  
    });  
    // #endif  
},  
async onShow() {  
    let that = this;
    // this.tabBerLists = uni.getStorageSync('tabBarList') // 自定义的tabbar赋值  
    // console.log("hasmore", that.hasMore)  
    let token = uni.getStorageSync('uni_id_token')  
    // console.log("Token", token)  
    if (token) {  
        let resuser = await db.collection("uni-id-users").where({  
                token: token  
            })  
            .field({  
                username: true,  
                userType: true,  
                realName: true,  
                wx_openid: true,  
                identitycard: true  
            })  
            .get()  
        // console.log("resuser", resuser)  

        if (resuser.data.length == 1) {  
            let userdata = resuser.data[0]  
            getApp().globalData.userName = userdata.username  
            getApp().globalData.realName = userdata.realName  
            getApp().globalData.userType = userdata.userType  
            getApp().globalData.adminType = userdata.userType  
            getApp().globalData.openid = userdata.wx_openid ? userdata.wx_openid.mp : ''  
            //未读消息  
            // console.log("userName:", getApp().globalData.userName)  
            var count = await db.collection('Messages')  
                .where({  
                    messageSend: getApp().globalData.userName,  
                    isRead: false  
                }).count()  
            // console.log("count:", count)  
            getApp().globalData.unreadMessages = count.total  
            //通过manager更新  
            let resmanager = await db.collection("Managers").where({  
                    userName: userdata.username  
                })  
                .get()  
            if (resmanager.data.length > 0) {  
                resmanager = resmanager.data[0]  
                getApp().globalData.adminType = resmanager.adminType  
                getApp().globalData.userDept = resmanager.department  
                getApp().globalData.adminLevel = resmanager.adminType  
                getApp().globalData.scopeCompany = resmanager.scopeCompany  
                getApp().globalData.division = resmanager.division  
                getApp().globalData.position = resmanager.position  
            }  

            if (resuser.data[0].userType == '供应商') {  
                getApp().globalData.userDept = '供应商'  

            }  
            if (resuser.data[0].userType == '管理员') {  
                that.$store.commit('setRoleId', 1)  
                getApp().globalData.setRoleId = 1  
                that.tabBerLists = uni.getStorageSync('tabBarList') // 自定义的tabbar赋值  
                if (that.tabBerLists.length == 4) {  
                    that.currenttab = 3  
                    that.tabBerLists[2].mark = getApp().globalData.unreadMessages  

                }  
            } else {  
                that.$store.commit('setRoleId', 0)  
                getApp().globalData.setRoleId = 0  
                that.tabBerLists = uni.getStorageSync('tabBarList')  
                if (that.tabBerLists.length == 4) {  
                    that.currenttab = 3  
                    that.tabBerLists[1].mark = getApp().globalData.unreadMessages  
                }  
            }  
        } else if (resuser.data.length == 0) {  
            uni.navigateTo({  
                url: "/pagessub/ucenter/pages/login/login-withpwd"  
            })  
        }  

    } else {  
        console.log("user has no token")  
        uni.showToast({  
            title: "未登录",  
            icon: 'none'  
        })  
        that.$store.commit('setRoleId', 0)  
        getApp().globalData.setRoleId = 0  
        that.tabBerLists = uni.getStorageSync('tabBarList')  
        if (that.tabBerLists.length == 4) {  
            that.currenttab = 3  
        }  
    }  

    // #ifndef MP-WEIXIN  
    let resp = await db.collection('Projects')  
        .where({  
            isShow: true  
        })  
        .orderBy('flag', 'desc')  
        .get()  

    if (resp.data) {  
        that.record = resp.data  
    } else {  
        uni.showToast({  
            title: "没有数据"  
        })  
    }  
    // #endif  

    // this.$refs.udb.loadData() //udb为unicloud-db组件的ref属性值  

}

操作步骤

打开uni统计2.0

预期结果

正确处理报错,不陷入死循环

实际结果

内存耗尽,首页无法打开

bug描述

升级到最新版HBuilderX4.45 正式版与alpha版发现的问题,编译到微信开发者工具测试内存很快耗尽,经排查发现,是uni统计代码造成的。关闭微信平台后,一切正常。首页代码很正常,没有死循环。目前只能暂时关闭统计。

Image Image


更多关于uni-app 统计2.0配置微信小程序平台导致内存耗尽崩溃的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

是 vue2 项目还是 vue3 项目 ?

更多关于uni-app 统计2.0配置微信小程序平台导致内存耗尽崩溃的实战教程也可以访问 https://www.itying.com/category-93-b0.html


已经复现,在排查了,修复后我会告知

在处理uni-app项目时,如果遇到因统计2.0配置微信小程序平台导致的内存耗尽崩溃问题,这通常与统计SDK的不当使用或者代码中存在内存泄漏有关。以下是一些可能的解决方案,主要通过代码示例展示如何优化统计SDK的使用和排查内存泄漏。

1. 优化统计SDK的使用

确保统计SDK的初始化只在需要时执行一次,并且正确管理其生命周期。例如,可以在App.vueonLaunch方法中初始化统计SDK,而不是在每个页面都重复初始化。

// App.vue
export default {
  onLaunch() {
    // 初始化统计SDK,仅执行一次
    if (!window.__STAT_INITIALIZED__) {
      const stat = require('path/to/your/stat-sdk');
      stat.init({
        // 配置项
      });
      window.__STAT_INITIALIZED__ = true;
    }
  },
  // ...其他生命周期函数
};

2. 避免全局变量导致的内存泄漏

全局变量如果不及时清理,会导致内存泄漏。尽量使用局部变量,或者使用Vue的响应式数据管理系统来管理状态。

// 避免全局变量
// let globalVar; // 不推荐

export default {
  data() {
    return {
      localVar: null, // 推荐使用局部变量或Vue的响应式数据
    };
  },
  // ...其他选项
};

3. 使用WeakMapWeakSet管理对象引用

对于需要缓存大量对象但又不想阻止垃圾回收的情况,可以使用WeakMapWeakSet

const weakMap = new WeakMap();

function cacheObject(obj, key, value) {
  if (!weakMap.has(obj)) {
    weakMap.set(obj, new Map());
  }
  weakMap.get(obj).set(key, value);
}

// 使用时,weakMap中的对象不会阻止垃圾回收

4. 定期清理定时器和事件监听器

定时器和事件监听器如果不及时清理,也会导致内存泄漏。

let timer;

export default {
  onShow() {
    clearTimeout(timer); // 清理之前的定时器
    timer = setTimeout(() => {
      // 执行某些操作
    }, 1000);
  },
  onHide() {
    clearTimeout(timer); // 页面隐藏时清理定时器
  },
  // ...其他选项
};

总结

以上代码示例展示了如何通过优化统计SDK的使用、避免全局变量、使用WeakMap/WeakSet管理对象引用以及定期清理定时器和事件监听器等方法来减少内存泄漏的风险。在实际项目中,还需要结合具体的使用场景和性能分析工具(如微信开发者工具的内存分析工具)来进一步定位和解决内存耗尽崩溃的问题。

回到顶部