You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny模块中ActionButton无法更新的问题求助

问题解决:Shiny模块中ActionButton标签和图标无法更新

问题原因

在模块的server函数里调用updateActionButton时,错误地用session$ns()包装了inputId。模块内部的session已经包含了命名空间上下文,直接使用按钮的原始ID("run")即可,重复包装会生成错误的ID,导致更新指令找不到目标按钮。

修正后的代码

nameUI <- function(id) {
  
  ns <- NS(id)
  tagList(
    actionButton(ns("run"), "Run", icon = icon("bolt"))
  )
}

nameServer <- function(id) {
  moduleServer(id, function(input, output, session) {

    observeEvent(input$run, {
      # 移除ns()包装,直接用"run"作为inputId
      updateActionButton(session, inputId = "run", label = "Running", icon = icon("sync", class = "fa-spin"))
      print("Running")
      Sys.sleep(3)
      updateActionButton(session, inputId = "run", label = "Run Done", icon = icon("bolt"))
      print("Done")
    })
    
  })
}

app <- function() {
  ui <- fluidPage(
    nameUI("test")
  )
  server <- function(input, output, session) {
    nameServer("test")
  }
  shinyApp(ui, server)  
}

app()

关键修改说明

  • UI部分的actionButton仍然需要用ns()生成ID,这是正确的写法
  • Server部分的updateActionButton中,inputId直接写"run"即可,模块的session会自动关联到正确的命名空间按钮
  • 注意:Sys.sleep(3)会阻塞Shiny的响应线程,实际业务场景建议用future包实现异步操作,避免界面冻结

内容的提问来源于stack exchange,提问作者MLEN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 04:07:04