Izale McLeod's hat-trick kept Barnet's hopes of avoiding the drop alive and also ended Gillingham's unbeaten run.
Mark Byrne put Barnet in front with a low shot, but the hosts levelled when Andy Barcham tapped in a rebound.
McLeod scored with a header, bundled the ball home for his second and grabbed his third from a spot-kick.
He then blazed a second penalty over the bar, before Barcham's fine finish gave Gillingham, who lost for the first time in 17 matches, a late consolation.
Gillingham trailed 3-1 when they conceded the first of two penalties as Matt Lawrence fouled Jack Midson in the area, which McLeod converted.
Midson was again fouled shortly afterwards, this time by Josh Gowling, but McLeod's extravagant chip went over the crossbar.
Barnet boss Guiliano Grazioli told BBC London 94.9:
"I can't praise the players enough - they've had a tough couple of weeks.
"They've shown a high standard, not just in the matches, but in training everyday.
"They are good and honest lads and they've shown people today that we're in a false position."
Gillingham boss Andy Hessenthaler told BBC Radio Kent:
"I didn't see that coming. We were too stretched as a team, defended very poorly, all the goals were avoidable and it summed the afternoon up.
"It's hard to be too critical because we've done well to get in this position, don't throw it all away now.
"Hopefully we can go and take it out on Rotherham on Monday."