hp0844182
V2EX  ›  问与答

引入 async 函数报: TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

  •  
  •   hp0844182 · Aug 10, 2019 · 4010 views
    This topic created in 2489 days ago, the information mentioned may be changed or developed.
    我在使用 electron-vue 开发时碰到这个问题:
    > 我在一个文件中定义一个 async 函数,然后按 commonJS 规范暴露出去。该代码如下:
    ```
    async function testAsync(){
    var a = 1;
    await a+2;
    return a
    }


    module.exports = {
    test
    }
    ```
    >但是报一个这样的错:TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

    >而当我去掉该函数的 async 以及 await 关键字之后又正常了。。。有点蒙蔽。。。
    7 replies    2019-08-10 16:52:38 +08:00
    des
        1
    des  
       Aug 10, 2019 via Android   ❤️ 1
    function testAsync 然后导出的是 test ?
    hp0844182
        2
    hp0844182  
    OP
       Aug 10, 2019
    写错了···导出的是 testAsync
    ochatokori
        3
    ochatokori  
       Aug 10, 2019 via Android
    好像是不能导出异步方法?
    你可以让这个方法返回一个 promise 在 promise 里面 await 但不要写成 async 方法
    POPOEVER
        4
    POPOEVER  
       Aug 10, 2019   ❤️ 1
    代码里用了 import 吗?如果用了,试试用 export default testAsync 代替 module.exports 看看
    hp0844182
        5
    hp0844182  
    OP
       Aug 10, 2019
    @POPOEVER 在主进程中全部用的 require,渲染进程里用的 import
    POPOEVER
        6
    POPOEVER  
       Aug 10, 2019   ❤️ 1
    @hp0844182 哦,反正 import 和 module.exports 不能混用就是了
    cuiweiqiang
        7
    cuiweiqiang  
       Aug 10, 2019 via iPhone
    用 exports.testAsync 试试
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1230 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 17:36 · PVG 01:36 · LAX 10:36 · JFK 13:36
    ♥ Do have faith in what you're doing.