众所周知在小程序里如果开启了ES6转ES5是没法用 async/await 的,但还是有解决办法的,搜到的解决方案都指向 runtime.js 这个文件。

但是Facebook在19年3月8号更新了runtime.js 的代码,用了 Function 函数,于是小程序里又不能用了,惊不惊喜。。。

解决办法

当然是把 Function 改回去,我已经改好并上传到Github了。

有需要的直接下载即可 点我下载runtime.js (蓝字可点,或者复制下方链接)。

https://github.com/xubaifuCode/regeneratorRuntime/tree/master复制代码

事情起因

为了封装request,简易代码如下

new Promise(async (resolve) = {      const result = await request(options);      resolve(result);    });复制代码

运行时发现错误(编辑器开启了ES6转ES5)

网上搜,都说是下载regenerator-runtime的库,例如

https://developers.weixin.qq.com/community/develop/doc/000a4ac7c7c108998916efda35b400https://blog.csdn.net/sinat_33184880/article/details/85533095复制代码

但是我引入之后出现了如下错误

VM9914:1 thirdScriptError sdk uncaught third Error  Function(...) is not a functionTypeError: Function(...) is not a function复制代码

错误原因是使用了 Function 函数, 小程序当然是拒绝使用这个不安全的函数的,于是就报错了。

既然在小程序里是不能使用 Fcnction 函数的,那为什么网上的解决方案都是这个呢?

于是我去GitHub仓库查看runtime.js的版本更新记录。

https://github.com/facebook/regenerator/commits/master/packages/regenerator-runtime/runtime.js复制代码

发现3月8号有一次更新,点进去就发现,新增的代码正是导致小程序报错的罪魁祸首。

修复这个问题也是很简单,删掉新增的try-catch语句,同时将var runtime改回var regeneratorRuntime即可。

人家为什么要改成用Function?

从上图中可以看到,是为了避免严格模式出错才用的 Function,还是大佬姿势多,学习一个。

TAG标签: 微信小程序es6转es5

http://www.xiaochengxub.com/read-102585.html