Fix panic due to overly long borrow of RefCell

Closes #18711
Add regression test for #18711
auto merge of #18729 : bkoropoff/rust/issue-18711, r=cmr

Closes #18711