Barnsley then took a quick free kick which allowed Conor Hourihane to take a shot on goal, but his left-footed effort hit the post.
Afobe eventually got the breakthrough after following up Mark Randall's drive to fire home.
Samir Carruthers then added a second for the visitors just before the half-time whistle by smashing into the top corner.
Highly-rated Dele Alli got MK Dons a third after the break, nutmegging a Barnsley defender before finishing with a deft chip.
Hourihane played a ball forward for Devante Cole to chase as Barnsley looked to claw a goal back, but the striker's touch was too heavy and Martin was able to come off his line and claim.
Barnsley showed admirable determination to fight back, however, and for a moment looked like they might pull off an unlikely comeback.
First, Hourihane produced two stunning strikes to reduce the deficit, before Devante Cole scored in the 90th minute.
It was too little, too late for the hosts as MK Dons went home from Yorkshire with a 5-3 victory.