Flex: RangeError 2006 and the re-parenting of UIComponents
I have been working with Flex recently and have found something that for a while foxed me completely. My application would crash when resized suddenly. That is, everything was broken, even buttons were not responding. The exception thrown (rangeError 2006 - index out of bounds) was from deep down in the framework, in the getChildAt method of DisplayObjectContainer, called by mx.core.Container. The root of the callstack showed callLaterDisparcher. Obviously a timing bug of some kind…
After a few experiments I found that this was due to multiple calls of my stage resize handler on the same frame. An obvious fix came to mind, but not a satisfactory one. By only accepting one call per frame the resize handler could be made stable, but this did not sit well. Why should this be necessary? Why should calling the same function twice on the same frame cause such catastrophic failure?
We set out to build a minimal case of the problem. Eventually we discovered the following test case which demonstrates our finding:
You can re-parent a UIComponent without removing it from its parent. But if you do this twice on the same frame, Flex will crash.
Of course, knowing this, the fix is simply to re-parent by removing and then adding. Well worth knowing if you are doing any reparenting.
NB This is different from how DisplayObjectContainer behaves.
NB This is fixed in Flex 3.