How to generate custom labels based on a state?

I would like to have refs that initially aren’t referencing anything, but at the end of the document, I would programmatically check all the refereces that aren’t referencing anything and generate labels for all of them. The idea is something like this:

@MyRef
...
// end of document
#generate-labels() // <- MyRef ends up pointing here

I’ve tried to do this with a custom function and a state variable, but every time I try to generate a label, it acts as if it was generated multiple times. What I’m trying to do:

#let unlabelled = state("labels", ())
#let make_ref(name) = {
  unlabelled.update(val => (..val, name)
  ref(label(name)) // ERROR: Label occurs multiple times in the document
}
...
// end of document
#context {
  let labels = unlabelled.final()
  show heading: set text(0pt)
  for label_name in labels [
    = Anchor #label(label_name)
  ]
}

Why is this generating labels multiple times? It also doesn’t work even if I remove the ref from the make_ref function and just reference the label normally. The context should only generate from the state once, right? Even when I look at the document, the anchor heading only gets generated once…

I’d really appreciate if this could work.

Never mind, I figured this out (literally, the solution is to use a figure and not a heading).

For some reason, when using heading, it breaks and says that multiple definitions have been generated, but when using a figure, it works just fine.