The exact same thing happened to me recently. I still don't quite understand why, but I think it could be some frame flex. You were mashing up a hill, possibly the chain was too loose combined with a little flex from the frame, and possibly the wheel moved a little bit in the dropouts. Scary ****. Chainline could have contributed to this as well. Be thankful this didn't cause you a serious injury.