ASP.NET Core Blazor中JS.InvokeAsync无返回值问题排查
解决Blazor中调用JS获取window.devicePixelRatio无响应的问题
问题根源
- 你在
OnAfterRender(void返回类型)中调用异步方法GetDevicePixelRatio()时未使用await,导致异步操作的异常被静默丢弃,后续代码无法正常执行。 - 未添加异常捕获逻辑,无法定位JS调用是否发生错误。
修复方案1:改用异步生命周期方法(推荐)
将OnAfterRender替换为OnAfterRenderAsync,通过await等待异步方法执行,同时添加异常捕获:
@inject IJSRuntime JS @code { private double m_dpiScale; protected override async Task OnAfterRenderAsync(bool firstRender) { await base.OnAfterRenderAsync(firstRender); if (firstRender) { await GetDevicePixelRatio(); } } private async Task GetDevicePixelRatio() { Console.WriteLine("GetDevicePixelRatio Calling"); try { m_dpiScale = await JS.InvokeAsync<double>("PixelRatio"); Console.WriteLine($"GetDevicePixelRatio Called with value {m_dpiScale}"); } catch (Exception ex) { Console.WriteLine($"获取devicePixelRatio失败: {ex.Message}"); } } }
修复方案2:在原方法中处理异步异常(不推荐)
如果必须保留OnAfterRender,可以通过后续任务捕获异常:
protected override void OnAfterRender(bool firstRender) { base.OnAfterRender(firstRender); if (firstRender) { _ = GetDevicePixelRatio().ContinueWith(task => { if (task.Exception != null) { Console.WriteLine($"异步调用出错: {task.Exception.InnerException?.Message}"); } }); } }
额外检查点
确保自定义JS脚本在Blazor初始化脚本之前加载,保证PixelRatio函数全局可用:
<body> <script> function PixelRatio() { return window.devicePixelRatio; } </script> <!-- Blazor脚本需在自定义脚本之后加载 --> <script src="_framework/blazor.webassembly.js"></script> </body>
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

