fix(admin): SQL 控制台 Ctrl+Enter 触发 panic(无 dioxus scope)

现象:编辑器有焦点时点击执行(或按 Ctrl+Enter)会 panic:
  called `Option::unwrap()` on a `None` value  (runtime.rs:223)
  RefCell already borrowed                       (runtime.rs:280)

根因:Ctrl+Enter 从 CodeMirror 的 JS 事件处理中触发 onRunShortcut
回调,此时 dioxus scope stack 为空。execute_for_editor 内部调
spawn(),而 spawn() 走 Runtime::with_current_scope →
current_scope_id().unwrap(),scope stack 空时直接 panic。
第二个 panic 是 unwind 期间再次 borrow scope_stack 触发的。

修复:用 dioxus 文档推荐的 web-sys 回调模式——在组件主体捕获
scope_id(此时 scope 活跃),JS 回调里用
Runtime::current().in_scope(scope_id, ...) 重建 scope 上下文
后再执行,spawn 即可找到 origin scope。

dioxus-core 源码(global_context.rs docstring)明示此模式,
dioxus-signals/src/global/mod.rs:201 也是这样用的。

注意:按钮 onclick 走 dioxus 事件系统(scope 已设),不受影响;
仅 CodeMirror JS 回调路径需要 in_scope 兜底。
This commit is contained in:
xfy 2026-07-05 21:59:17 +08:00
parent 81648de16f
commit 2cfc64b319

View File

@ -710,7 +710,7 @@ fn SqlConsoleTab() -> Element {
// 用两个独立闭包execute_for_editor / run_sql避免 move 单一所有权冲突——
// 它们捕获相同的 Copy signal行为完全等价。
#[cfg(target_arch = "wasm32")]
let execute_for_editor = move || {
let mut execute_for_editor = move || {
running.set(true);
error.set(None);
let sql = sql_text.read().clone();
@ -746,6 +746,14 @@ fn SqlConsoleTab() -> Element {
});
};
// 捕获当前 scope idCtrl+Enter 从 CodeMirror 的 JS 事件处理中触发时,
// dioxus scope stack 为空spawn() 内部 current_scope_id().unwrap() 会 panic。
// 在 effect 里用 Runtime::in_scope 重建 scope 上下文,保证 spawn 找得到 origin。
#[cfg(target_arch = "wasm32")]
let scope_id = dioxus::core::Runtime::current()
.try_current_scope_id()
.unwrap_or(dioxus::core::ScopeId::ROOT);
// 初始化 CodeMirror + 拉取 schema 注入补全。仅 WASM。
#[cfg(target_arch = "wasm32")]
{
@ -760,7 +768,12 @@ fn SqlConsoleTab() -> Element {
});
let on_ready = Closure::new(|| {});
// Ctrl/Cmd+Enter 触发执行(与按钮共用同一套资源/护栏逻辑)。
let on_run_shortcut = Closure::new(execute_for_editor);
// 从 CodeMirror JS 事件触发时无 dioxus scope必须用 in_scope 重建。
// execute_for_editor 是 Fn只捕获 Copy signal借用调用即可。
let on_run_shortcut = Closure::new(move || {
dioxus::core::Runtime::current()
.in_scope(scope_id, || execute_for_editor());
});
let theme_name = if resolved() == ResolvedTheme::Dark { "dark" } else { "light" };
let opts = codemirror_bridge::EditorOptions::new();