Node.js应用报错:await仅允许在async函数及模块顶层使用(index.js:13:21)
错误排查:Only valid in async functions and the top level bodies of modules
报错信息
Only valid in async functions and the top level bodies of modules (at index.js:13:21)
相关代码
异步函数定义
async function run() { console.log("running..."); const config = { auth: { clientId: 'xxxxxxxxxxxxxxxxxxxx', authority: 'https://login.microsoftonline.com/organizations/', redirectUri: 'http://localhost:8080' } }; var client = new msal.PublicClientApplication(config); var loginRequest = { scopes: [ 'user.read' ] }; let loginResponse = await client.loginPopup(loginRequest); console.log('Login Response', loginResponse); }
触发按钮
<button type="button" class="btn btn-primary btn-lg" onclick="run()"> <i class="fa fa-fw fa-inverse fa-play"></i> Run Code </button>
错误原因
- 同名函数覆盖:页面中可能存在其他普通
run函数定义,覆盖了异步版本的run,导致执行时函数内部的await处于非异步环境,触发报错。 - 脚本加载模式问题:若脚本未以模块(
type="module")方式加载,部分旧环境对异步函数内的await支持存在兼容限制。 - msal库未正确加载:如果
msal对象未被正确引入,可能导致后续逻辑异常,间接引发类似报错(但此场景下通常会有"msal is not defined"的前置报错)。
解决办法
- 排查函数冲突:在
run函数开头添加console.log(run),确认输出的函数是否带有async标识;检查页面所有脚本,删除或重命名其他同名的run函数。 - 切换为模块加载脚本:在引入index.js的
<script>标签中添加type="module"属性,示例:
模块模式不仅能提升异步语法兼容性,还能隔离全局作用域,避免函数冲突。<script type="module" src="index.js"></script> - 兼容旧环境:若需要支持不兼容
async/await的旧版浏览器,使用Babel等工具将代码转译为ES5兼容语法。 - 验证msal加载:在
run函数开头添加console.log(msal),确认msal对象存在且PublicClientApplication属性正常。
内容的提问来源于stack exchange,提问作者S_A
相关产品推荐
相关产品推荐

