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

Shiny应用模块化改造后出现sink stack is full错误及输出异常

问题排查与修复

核心问题分析

  1. 错误赋值导致存储异常:你在server中执行了nameList(newNameServer("newName", nameList)),这相当于把newNameServer返回的reactiveVal函数对象直接存入了nameList这个响应式变量中,所以输出会出现函数结构的字符串,而非预期的字符向量。
  2. 模块返回值冗余:newNameServer模块不需要返回nameList,因为reactiveVal是引用类型,模块内部对它的修改会直接作用于外部的变量,返回反而引发错误赋值。
  3. 初始值处理不当:nameList <- reactiveVal()初始化的是NULL值,首次append时会把NULL和输入值拼接,触发sink stack is full错误,同时导致输出结构异常。

修复后的完整代码

library(shiny)

newNameUI <- function(id) {
  ns <- NS(id)
  tagList(
    textInput(ns("name"), "Name:"),
    actionButton(ns("btnSave"), "Save")
  )
}

listNamesUI <- function(id) {
  ns <- NS(id)
  tagList(
    h5("Output:"),
    verbatimTextOutput(ns("out"))
  )
}

newNameServer <- function(id, nameList) {
  moduleServer(id, function(input, output, session) {
    # 处理初始空值,避免拼接NULL
    observeEvent(input$btnSave, {
      current <- nameList()
      if(is.null(current)) {
        nameList(c(input$name))
      } else {
        nameList(append(current, input$name))
      }
    })
    # 移除不必要的return语句
  })
}

listNamesServer <- function(id, nameList) {
  moduleServer(id, function(input, output, session) {
    output$out <- renderPrint(nameList())
  })
}

ui <- fluidPage(
  fluidRow(newNameUI("newName")),
  fluidRow(listNamesUI("listNames"))
)

server <- function(input, output, session) {
  # 初始化空字符向量,而非NULL
  nameList <- reactiveVal(character(0))
  
  # 直接调用模块,无需赋值给nameList
  newNameServer("newName", nameList)
  
  listNamesServer("listNames", nameList)
}

shinyApp(ui, server)

关键改动说明

  • 移除newNameServer中的return(nameList),模块仅负责修改传入的响应式变量。
  • 初始化nameList为character(0)(空字符向量),避免首次拼接时的NULL问题。
  • server中直接调用newNameServer("newName", nameList),不再将返回值赋值给nameList。
  • 模块内的observeEvent增加了初始值判断,确保第一次添加名称时能正确生成字符向量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:40:25